import 'dart:convert';
import 'dart:math' as math;

import 'package:amap_map_fluttify/amap_map_fluttify.dart';
import 'package:detect/entity/entity.dart';
import 'package:detect/notifier/chat.dart';
import 'package:detect/notifier/detect.dart';
import 'package:detect/notifier/fpga_time.dart';
import 'package:detect/notifier/location.dart';
import 'package:detect/notifier/radio_control.dart';
import 'package:detect/notifier/radio_target.dart';
import 'package:detect/notifier/state.dart';
import 'package:detect/pages/about_detect.dart';
import 'package:detect/utils/api_util.dart';
import 'package:detect/utils/db_util.dart';
import 'package:detect/utils/detect_util.dart';
import 'package:detect/utils/global.dart';
import 'package:detect/utils/iconfont.dart';
import 'package:detect/utils/image_util.dart';
import 'package:detect/utils/modal_util.dart';
import 'package:detect/utils/option_util.dart';
import 'package:detect/utils/storage_util.dart';
import 'package:detect/utils/toast_util.dart';
import 'package:detect/utils/ws_util.dart';
import 'package:detect/widgets/amap.dart';
import 'package:detect/widgets/animated_loop.dart';
import 'package:detect/widgets/chart.dart';
import 'package:detect/widgets/custom_table.dart';
import 'package:detect/widgets/dropdown.dart';
import 'package:detect/widgets/future_widget.dart';
import 'package:detect/widgets/input_field.dart';
import 'package:detect/widgets/other/custom_scroll_behavior.dart';
import 'package:detect/widgets/resize_state_builder.dart';
import 'package:flutter/material.dart';
import 'package:flutter_color_plugin/flutter_color_plugin.dart';
import 'package:flutter_keyboard_visibility/flutter_keyboard_visibility.dart';
import 'package:log4f/log4f.dart';
import 'package:provider/provider.dart';

class Home extends StatefulWidget {
  const Home({super.key});

  @override
  State<Home> createState() => _HomeState();
}

class _HomeState extends State<Home> {
  final GlobalObjectKey _navKey = const GlobalObjectKey("nav");
  final List<String> _navList = ["台站管理", "频谱监测", "连续探测", "选频探测", "传输服务"];
  final PageController _pageController = PageController();
  int _navIndex = 0;

  @override
  void initState() {
    WSUtil.connect().listener([
      ReceiveMsgListener("error", (response) {
        int value = response['value'];
        if (value == 3) {
          ModalUtil.dialog(
            context: context,
            resizeToAvoidBottomInset: false,
            barrierDismissible: false,
            width: Global.ds(320),
            height: Global.ds(160),
            child: Container(
              alignment: Alignment.center,
              clipBehavior: Clip.antiAlias,
              padding: EdgeInsets.all(Global.ds(20)),
              decoration: BoxDecoration(color: ColorUtil.color("#1A3959"), borderRadius: BorderRadius.circular(Global.ds(16))),
              child: Column(
                mainAxisSize: MainAxisSize.min,
                mainAxisAlignment: MainAxisAlignment.center,
                crossAxisAlignment: CrossAxisAlignment.center,
                children: [
                  Text("终端服务已掉线", textAlign: TextAlign.center, style: TextStyle(fontSize: Global.ds(18), color: Colors.white)),
                  Divider(height: Global.ds(40), color: Colors.transparent),
                  TextButton(
                    onPressed: () => ApiUtil().reset().then((value) => Navigator.pop(context)),
                    style: TextButton.styleFrom(
                      textStyle: TextStyle(fontSize: Global.ds(18)),
                      fixedSize: Size(Global.ds(120), Global.ds(40)),
                      foregroundColor: Colors.white,
                      backgroundColor: ColorUtil.color("#2CA6E0"),
                    ),
                    child: const Text("重启服务"),
                  ),
                ],
              ),
            ),
          );
        }
        return false;
      }),
    ]);
    super.initState();
  }

  @override
  Widget build(BuildContext context) => WillPopScope(
        child: KeyboardDismissOnTap(
          child: FutureWidget<String>(
            future: context.read<StateNotifier>().initTime,
            loadingDesc: "等待终端初始化",
            doneBuilder: (context, snapshot) {
              Map<String, dynamic> status = context.read<StateNotifier>().state;
              this.context.read<FpgaTimeNotifier>().init(snapshot.requireData);
              if (status['detecting'] == false) DetectUtil.instance.detecting = null;
              this.context.read<DetectNotifier>().init(this.context);
              this.context.read<ChatNotifier>().init(this.context);
              return Column(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                crossAxisAlignment: CrossAxisAlignment.stretch,
                children: [
                  _header,
                  Expanded(
                    child: Container(
                      padding: EdgeInsets.only(left: Global.ds(15), right: Global.ds(15), bottom: Global.ds(15)),
                      decoration: BoxDecoration(
                        gradient: RadialGradient(
                          colors: [ColorUtil.color("#012D80"), ColorUtil.color("#000724")],
                          stops: const [0, 1],
                        ),
                      ),
                      child: PageView(
                        controller: _pageController,
                        scrollBehavior: const CustomScrollBehavior(),
                        onPageChanged: (index) => _navKey.currentState?.setState(() => _navIndex = index),
                        children: [
                          Row(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            crossAxisAlignment: CrossAxisAlignment.stretch,
                            children: [
                              const Expanded(child: MapView()),
                              VerticalDivider(width: Global.ds(10), color: Colors.transparent),
                              Expanded(
                                child: Material(
                                  clipBehavior: Clip.antiAlias,
                                  color: ColorUtil.color("#1A3959"),
                                  borderRadius: BorderRadius.circular(Global.ds(16)),
                                  child: const RadioList(),
                                ),
                              ),
                            ],
                          ),
                          const Spectrum(),
                          const DetectGeneral(),
                          const DetectPick(),
                          const Transmission(),
                        ],
                      ),
                    ),
                  ),
                ],
              );
            },
          ),
        ),
        onWillPop: () async => false,
      );

  ///计算驻波值
  double _vswr(double forewordPower, double backPower) {
    double r = forewordPower / backPower;
    double rl = -10 * r > 0 ? math.log(r) : 0;
    double t = 10 * (-rl / 20);
    rl = -20 * t > 0 ? math.log(t) : 0;
    return (1 + t) / (1 - t);
  }

  Widget get _header => Container(
        height: Global.ds(120),
        color: ColorUtil.color("#000724"),
        padding: EdgeInsets.symmetric(horizontal: Global.ds(15)),
        child: Stack(
          alignment: Alignment.topCenter,
          children: [
            Positioned(
              top: Global.ds(15),
              left: Global.ds(0),
              right: Global.ds(195),
              height: Global.ds(90),
              child: Container(
                clipBehavior: Clip.antiAlias,
                decoration: BoxDecoration(
                  borderRadius: BorderRadius.only(
                    topLeft: Radius.circular(Global.ds(45)),
                    bottomLeft: Radius.circular(Global.ds(45)),
                    bottomRight: Radius.circular(Global.ds(22.5)),
                  ),
                  color: ColorUtil.color("#022347"),
                ),
                child: Row(mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [_nav, _deviceInfo]),
              ),
            ),
            Positioned(
              top: Global.ds(15),
              right: Global.ds(0),
              width: Global.ds(195),
              height: Global.ds(45),
              child: Container(
                clipBehavior: Clip.antiAlias,
                decoration: BoxDecoration(
                  borderRadius: BorderRadius.only(topRight: Radius.circular(Global.ds(22.5)), bottomRight: Radius.circular(Global.ds(22.5))),
                  color: ColorUtil.color("#022347"),
                ),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    ImageUtil.icon("static/images/icon/3.png", size: Global.ds(20), color: Colors.white),
                    VerticalDivider(width: Global.ds(5), color: Colors.transparent),
                    Consumer<FpgaTimeNotifier>(
                      builder: (context, notifier, child) => Text(notifier.format(), style: TextStyle(fontSize: Global.ds(24), color: Colors.white)),
                    ),
                  ],
                ),
              ),
            ),
            Positioned(
              top: Global.ds(60),
              right: Global.ds(0),
              width: Global.ds(195),
              height: Global.ds(45),
              child: Container(color: ColorUtil.color("#022347")),
            ),
            Positioned(
              top: Global.ds(60),
              right: Global.ds(0),
              width: Global.ds(195),
              height: Global.ds(45),
              child: Container(
                clipBehavior: Clip.antiAlias,
                decoration: BoxDecoration(
                  borderRadius: BorderRadius.only(topLeft: Radius.circular(Global.ds(22.5))),
                  color: ColorUtil.color("#000724"),
                ),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    VerticalDivider(width: Global.ds(6.5), color: Colors.transparent),
                    Expanded(
                      flex: 2,
                      child: GestureDetector(
                        onTap: () => ModalUtil.drawer(context: context, title: "设置", width: Global.ds(620), radius: Global.ds(16), child: const Setting()),
                        child: Container(
                          height: Global.ds(32),
                          alignment: Alignment.center,
                          clipBehavior: Clip.antiAlias,
                          padding: EdgeInsets.symmetric(horizontal: Global.ds(10)),
                          decoration: BoxDecoration(
                            border: Border.all(color: ColorUtil.color("#2A8FA7")),
                            borderRadius: BorderRadius.circular(Global.ds(16)),
                            gradient: LinearGradient(
                              begin: Alignment.topCenter,
                              end: Alignment.bottomCenter,
                              colors: [ColorUtil.color("#034470"), ColorUtil.color("#036EB7")],
                              stops: const [0, 1],
                            ),
                          ),
                          child: Row(
                            children: [
                              ImageUtil.icon("static/images/icon/4.png", size: Global.ds(20), color: ColorUtil.color("#66FFFB")),
                              VerticalDivider(width: Global.ds(2), color: Colors.transparent),
                              Text("设置", style: TextStyle(fontSize: Global.ds(14), height: 1, color: ColorUtil.color("#66FFFB")), maxLines: 1, softWrap: false),
                            ],
                          ),
                        ),
                      ),
                    ),
                    VerticalDivider(width: Global.ds(5), color: Colors.transparent),
                    Expanded(
                      flex: 3,
                      child: GestureDetector(
                        onTap: () => ModalUtil.drawer(
                          context: context,
                          title: "基础传输",
                          width: Global.ds(620),
                          radius: Global.ds(16),
                          child: const DataRW(),
                        ),
                        child: Container(
                          height: Global.ds(32),
                          alignment: Alignment.center,
                          clipBehavior: Clip.antiAlias,
                          padding: EdgeInsets.symmetric(horizontal: Global.ds(10)),
                          decoration: BoxDecoration(
                            border: Border.all(color: ColorUtil.color("#2A8FA7")),
                            borderRadius: BorderRadius.circular(Global.ds(16)),
                            gradient: LinearGradient(
                              begin: Alignment.topCenter,
                              end: Alignment.bottomCenter,
                              colors: [ColorUtil.color("#034470"), ColorUtil.color("#036EB7")],
                              stops: const [0, 1],
                            ),
                          ),
                          child: Text("基础传输", style: TextStyle(fontSize: Global.ds(14), height: 1, color: ColorUtil.color("#66FFFB")), maxLines: 1, softWrap: false),
                        ),
                      ),
                    ),
                  ],
                ),
              ),
            ),
            Container(
              width: Global.ds(320),
              height: Global.ds(50),
              alignment: Alignment.center,
              clipBehavior: Clip.antiAlias,
              decoration: BoxDecoration(
                borderRadius: BorderRadius.only(bottomLeft: Radius.circular(Global.ds(35)), bottomRight: Radius.circular(Global.ds(35))),
                color: ColorUtil.color("#000724"),
              ),
              child: ImageUtil.asset("static/images/title.png", width: Global.ds(256), height: Global.ds(33)),
            ),
            _radio,
          ],
        ),
      );

  Widget get _deviceInfo => Consumer<StateNotifier>(
        builder: (context, notifier, child) => Container(
          margin: EdgeInsets.only(right: Global.ds(15), top: Global.ds(15), bottom: Global.ds(15)),
          child: DefaultTextStyle(
            style: TextStyle(fontSize: Global.ds(14), height: 1.25, color: ColorUtil.color("#0C77A8")),
            child: GestureDetector(
              // behavior: HitTestBehavior.opaque,
              onTap: () => ModalUtil.drawer(
                context: context,
                title: "更多基础信息",
                width: Global.ds(620),
                radius: Global.ds(16),
                child: Consumer<StateNotifier>(
                  builder: (context, notifier, child) => Padding(
                    padding: EdgeInsets.all(Global.ds(40)),
                    child: Column(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Row(
                          mainAxisSize: MainAxisSize.min,
                          children: [
                            SizedBox(
                              width: Global.ds(96),
                              child: Text("服务状态：", style: TextStyle(fontSize: Global.ds(18), color: ColorUtil.color("#2CA6E0")), textAlign: TextAlign.right),
                            ),
                            Text("正常", style: TextStyle(fontSize: Global.ds(18), fontWeight: FontWeight.w700, color: ColorUtil.color("#97DEFF"))),
                          ],
                        ),
                        const Spacer(),
                        Row(
                          mainAxisSize: MainAxisSize.min,
                          children: [
                            SizedBox(
                              width: Global.ds(96),
                              child: Text("GPS位置：", style: TextStyle(fontSize: Global.ds(18), color: ColorUtil.color("#2CA6E0")), textAlign: TextAlign.right),
                            ),
                            Text(notifier.state['location'], style: TextStyle(fontSize: Global.ds(18), fontWeight: FontWeight.w700, color: ColorUtil.color("#97DEFF"))),
                          ],
                        ),
                        Row(
                          mainAxisSize: MainAxisSize.min,
                          children: [
                            SizedBox(
                              width: Global.ds(96),
                              child: Text("GPS时间：", style: TextStyle(fontSize: Global.ds(18), color: ColorUtil.color("#2CA6E0")), textAlign: TextAlign.right),
                            ),
                            Text(notifier.state['fpga_time'], style: TextStyle(fontSize: Global.ds(18), fontWeight: FontWeight.w700, color: ColorUtil.color("#97DEFF"))),
                          ],
                        ),
                        Row(
                          mainAxisSize: MainAxisSize.min,
                          children: [
                            SizedBox(
                              width: Global.ds(96),
                              child: Text("台站状态：", style: TextStyle(fontSize: Global.ds(18), color: ColorUtil.color("#2CA6E0")), textAlign: TextAlign.right),
                            ),
                            Text(RadioState.values[notifier.state['fpga_state']].name, style: TextStyle(fontSize: Global.ds(18), fontWeight: FontWeight.w700, color: ColorUtil.color("#97DEFF"))),
                          ],
                        ),
                        Row(
                          mainAxisSize: MainAxisSize.min,
                          children: [
                            SizedBox(
                              width: Global.ds(96),
                              child: Text("台站温度：", style: TextStyle(fontSize: Global.ds(18), color: ColorUtil.color("#2CA6E0")), textAlign: TextAlign.right),
                            ),
                            Text("${notifier.state['temperature']}℃", style: TextStyle(fontSize: Global.ds(18), fontWeight: FontWeight.w700, color: ColorUtil.color("#97DEFF"))),
                          ],
                        ),
                        Row(
                          mainAxisSize: MainAxisSize.min,
                          children: [
                            SizedBox(
                              width: Global.ds(96),
                              child: Text("台站电流：", style: TextStyle(fontSize: Global.ds(18), color: ColorUtil.color("#2CA6E0")), textAlign: TextAlign.right),
                            ),
                            Text("${notifier.state['electrical_current']}A", style: TextStyle(fontSize: Global.ds(18), fontWeight: FontWeight.w700, color: ColorUtil.color("#97DEFF"))),
                          ],
                        ),
                        Row(
                          mainAxisSize: MainAxisSize.min,
                          children: [
                            SizedBox(
                              width: Global.ds(96),
                              child: Text("台站功率：", style: TextStyle(fontSize: Global.ds(18), color: ColorUtil.color("#2CA6E0")), textAlign: TextAlign.right),
                            ),
                            Text(PowerType.values[notifier.state['power']].name, style: TextStyle(fontSize: Global.ds(18), fontWeight: FontWeight.w700, color: ColorUtil.color("#97DEFF"))),
                          ],
                        ),
                        Row(
                          mainAxisSize: MainAxisSize.min,
                          children: [
                            SizedBox(
                              width: Global.ds(96),
                              child: Text("正向功率：", style: TextStyle(fontSize: Global.ds(18), color: ColorUtil.color("#2CA6E0")), textAlign: TextAlign.right),
                            ),
                            Text("${(notifier.state['electrical_current'] ?? 0) * (notifier.state['foreword_power'] ?? 0)}",
                                style: TextStyle(fontSize: Global.ds(18), fontWeight: FontWeight.w700, color: ColorUtil.color("#97DEFF"))),
                          ],
                        ),
                        Row(
                          mainAxisSize: MainAxisSize.min,
                          children: [
                            SizedBox(
                              width: Global.ds(96),
                              child: Text("反向功率：", style: TextStyle(fontSize: Global.ds(18), color: ColorUtil.color("#2CA6E0")), textAlign: TextAlign.right),
                            ),
                            Text("${(notifier.state['electrical_current'] ?? 0) * (notifier.state['bakc_power'] ?? 0)}",
                                style: TextStyle(fontSize: Global.ds(18), fontWeight: FontWeight.w700, color: ColorUtil.color("#97DEFF"))),
                          ],
                        ),
                        Row(
                          mainAxisSize: MainAxisSize.min,
                          children: [
                            SizedBox(
                              width: Global.ds(96),
                              child: Text("功放状态：", style: TextStyle(fontSize: Global.ds(18), color: ColorUtil.color("#2CA6E0")), textAlign: TextAlign.right),
                            ),
                            Text(notifier.state['amp_opened'] ? "ON" : "OFF", style: TextStyle(fontSize: Global.ds(18), fontWeight: FontWeight.w700, color: ColorUtil.color("#97DEFF"))),
                          ],
                        ),
                        Row(
                          mainAxisSize: MainAxisSize.min,
                          children: [
                            SizedBox(
                              width: Global.ds(96),
                              child: Text("频谱状态：", style: TextStyle(fontSize: Global.ds(18), color: ColorUtil.color("#2CA6E0")), textAlign: TextAlign.right),
                            ),
                            Text(notifier.state['pp1'] == 0 ? "OFF" : "ON", style: TextStyle(fontSize: Global.ds(18), fontWeight: FontWeight.w700, color: ColorUtil.color("#97DEFF"))),
                          ],
                        ),
                        Row(
                          mainAxisSize: MainAxisSize.min,
                          children: [
                            SizedBox(
                              width: Global.ds(96),
                              child: Text("声波通道：", style: TextStyle(fontSize: Global.ds(18), color: ColorUtil.color("#2CA6E0")), textAlign: TextAlign.right),
                            ),
                            Text("${notifier.state['ddc_state']}", style: TextStyle(fontSize: Global.ds(18), fontWeight: FontWeight.w700, color: ColorUtil.color("#97DEFF"))),
                          ],
                        ),
                        const Spacer(),
                        Row(
                          mainAxisSize: MainAxisSize.min,
                          children: [
                            SizedBox(
                              width: Global.ds(96),
                              child: Text("探测状态：", style: TextStyle(fontSize: Global.ds(18), color: ColorUtil.color("#2CA6E0")), textAlign: TextAlign.right),
                            ),
                            Text(notifier.state['detecting'] ? "是" : "否", style: TextStyle(fontSize: Global.ds(18), fontWeight: FontWeight.w700, color: ColorUtil.color("#97DEFF"))),
                          ],
                        ),
                        Row(
                          mainAxisSize: MainAxisSize.min,
                          children: [
                            SizedBox(
                              width: Global.ds(96),
                              child: Text("探测类型：", style: TextStyle(fontSize: Global.ds(18), color: ColorUtil.color("#2CA6E0")), textAlign: TextAlign.right),
                            ),
                            Text(
                                notifier.state['detecting']
                                    ? notifier.state['detect_type'] == 'continue'
                                        ? "连续探测"
                                        : "选频探测"
                                    : "无",
                                style: TextStyle(fontSize: Global.ds(18), fontWeight: FontWeight.w700, color: ColorUtil.color("#97DEFF"))),
                          ],
                        ),
                        Row(
                          mainAxisSize: MainAxisSize.min,
                          children: [
                            SizedBox(
                              width: Global.ds(96),
                              child: Text("探测角色：", style: TextStyle(fontSize: Global.ds(18), color: ColorUtil.color("#2CA6E0")), textAlign: TextAlign.right),
                            ),
                            Text(
                              notifier.state['detecting'] ? DetectRole.values.byName(notifier.state['detect_role']).label : "无",
                              style: TextStyle(fontSize: Global.ds(18), fontWeight: FontWeight.w700, color: ColorUtil.color("#97DEFF")),
                            ),
                          ],
                        ),
                        Row(
                          mainAxisSize: MainAxisSize.min,
                          children: [
                            SizedBox(
                              width: Global.ds(96),
                              child: Text("探测台站：", style: TextStyle(fontSize: Global.ds(18), color: ColorUtil.color("#2CA6E0")), textAlign: TextAlign.right),
                            ),
                            Text(
                              notifier.state['detecting'] ? "${notifier.state['detect_remote_id']}" : "无",
                              style: TextStyle(fontSize: Global.ds(18), fontWeight: FontWeight.w700, color: ColorUtil.color("#97DEFF")),
                            ),
                          ],
                        ),
                      ],
                    ),
                  ),
                ),
              ),
              child: notifier.state['fpga_state'] > 0
                  ? Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      crossAxisAlignment: CrossAxisAlignment.end,
                      children: [
                        Column(
                          mainAxisAlignment: MainAxisAlignment.end,
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Row(
                              crossAxisAlignment: CrossAxisAlignment.end,
                              children: notifier.state['fpga_state'] > 1
                                  ? [
                                      ImageUtil.icon("static/images/state/state.send.png", size: Global.ds(20), color: ColorUtil.color("#FBD580")),
                                      VerticalDivider(width: Global.ds(5), color: Colors.transparent),
                                      Text("发射中...", style: TextStyle(fontSize: Global.ds(18), color: ColorUtil.color("#FBD580"))),
                                    ]
                                  : [
                                      ImageUtil.icon("static/images/state/state.receive.png", size: Global.ds(20), color: ColorUtil.color("#089F75")),
                                      VerticalDivider(width: Global.ds(5), color: Colors.transparent),
                                      Text("接收中...", style: TextStyle(fontSize: Global.ds(18), color: ColorUtil.color("#089F75"))),
                                    ],
                            ),
                            notifier.state['fpga_state'] > 1
                                ? Text("发射频率:${Global.toFixed(notifier.state['send_freq'] / 1000000, 3)}MHz")
                                : Text("接收频率:${Global.toFixed(notifier.state['receive_freq'] / 1000000, 3)}MHz"),
                            Text("${notifier.state['fpga_state'] > 1 ? '发射' : '接收'}功率:${PowerType.values[notifier.state['power'] ?? 0].name}"),
                          ],
                        ),
                        VerticalDivider(width: Global.ds(10), color: Colors.transparent),
                        Column(
                          mainAxisAlignment: MainAxisAlignment.end,
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Text("电流:${Global.toFixed(notifier.state['electrical_current'] ?? 0, 1)}A"),
                            Text(
                                "驻波:${Global.toFixed(_vswr((notifier.state['electrical_current'] ?? 0) * (notifier.state['foreword_power'] ?? 0), (notifier.state['electrical_current'] ?? 0) * (notifier.state['back_power'] ?? 0)), 1)}"),
                            Text("温度:${Global.toFixed(notifier.state['temperature'] ?? 0, 1)}℃"),
                          ],
                        ),
                      ],
                    )
                  : Row(
                      mainAxisSize: MainAxisSize.min,
                      crossAxisAlignment: CrossAxisAlignment.end,
                      children: [
                        Column(
                          mainAxisSize: MainAxisSize.min,
                          mainAxisAlignment: MainAxisAlignment.end,
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Row(
                              mainAxisSize: MainAxisSize.min,
                              mainAxisAlignment: MainAxisAlignment.center,
                              crossAxisAlignment: CrossAxisAlignment.center,
                              children: [
                                ImageUtil.icon("static/images/state/state.idle.png", size: Global.ds(20), color: ColorUtil.color("#9A9DAA")),
                                VerticalDivider(width: Global.ds(5), color: Colors.transparent),
                                Text("空闲中...", style: TextStyle(fontSize: Global.ds(18), color: ColorUtil.color("#9A9DAA"))),
                              ],
                            ),
                          ],
                        ),
                        VerticalDivider(width: Global.ds(10), color: Colors.transparent),
                        Column(
                          mainAxisSize: MainAxisSize.min,
                          mainAxisAlignment: MainAxisAlignment.end,
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Text("电流:${Global.toFixed(notifier.state['electrical_current'] ?? 0, 1)}A"),
                            Text(
                                "驻波:${Global.toFixed(_vswr((notifier.state['electrical_current'] ?? 0) * (notifier.state['foreword_power'] ?? 0), (notifier.state['electrical_current'] ?? 0) * (notifier.state['back_power'] ?? 0)), 1)}"),
                            Text("温度:${Global.toFixed(notifier.state['temperature'] ?? 0, 1)}℃"),
                          ],
                        ),
                      ],
                    ),
            ),
          ),
        ),
      );

  Widget get _nav => Container(
        width: Global.ds(450),
        height: Global.ds(60),
        margin: EdgeInsets.only(left: Global.ds(15), top: Global.ds(15), bottom: Global.ds(15)),
        child: StatefulBuilder(
          key: _navKey,
          builder: (context, stateSetter) => Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            crossAxisAlignment: CrossAxisAlignment.stretch,
            children: _navList
                .asMap()
                .keys
                .map((i) => Expanded(
                      child: GestureDetector(
                        onTap: () => _pageController.jumpToPage(i),
                        child: Container(
                          alignment: Alignment.center,
                          clipBehavior: Clip.antiAlias,
                          decoration: BoxDecoration(
                            border: Border.all(color: ColorUtil.color("#74C8CE")),
                            borderRadius: i == 0
                                ? BorderRadius.only(topLeft: Radius.circular(Global.ds(30)), bottomLeft: Radius.circular(Global.ds(30)))
                                : i == _navList.length - 1
                                    ? BorderRadius.only(topRight: Radius.circular(Global.ds(30)), bottomRight: Radius.circular(Global.ds(30)))
                                    : null,
                            gradient: LinearGradient(
                              begin: Alignment.topCenter,
                              end: Alignment.bottomCenter,
                              colors: _navIndex == i
                                  ? [ColorUtil.color("#17EFFF"), ColorUtil.color("#0197D3")]
                                  : [ColorUtil.color("#0E3344"), ColorUtil.color("#125B7E"), ColorUtil.color("#0A405A"), ColorUtil.color("#003752"), ColorUtil.color("#0080BE")],
                              stops: _navIndex == i ? [0, 1] : [.2, .46, .46, .66, .98],
                            ),
                          ),
                          child: Text(_navList[i], style: TextStyle(fontSize: Global.ds(16), color: Colors.white.withOpacity(.65))),
                        ),
                      ),
                    ))
                .toList(),
          ),
        ),
      );

  Widget get _radio => Container(
        width: Global.ds(280),
        height: Global.ds(55),
        margin: EdgeInsets.only(top: Global.ds(50)),
        alignment: Alignment.center,
        child: Consumer<RadioControlNotifier>(
          builder: (context, notifier, child) => FutureWidget<RadioEntity?>(
            future: DBApi.radio.localRadio(context.read<StateNotifier>().localId),
            doneBuilder: (context, snapshot) => snapshot.data == null
                ? Text("请先初始化台站设置", style: TextStyle(fontSize: Global.ds(18), color: ColorUtil.color("#ABDBF3")))
                : Column(
                    mainAxisSize: MainAxisSize.min,
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      Text("ID-${snapshot.data?.id}", style: TextStyle(fontSize: Global.ds(16), color: ColorUtil.color("#ABDBF3"))),
                      Text("${snapshot.data?.name}", style: TextStyle(fontSize: Global.ds(18), color: ColorUtil.color("#ABDBF3"))),
                    ],
                  ),
          ),
        ),
      );
}

class MapView extends StatefulWidget {
  const MapView({super.key});

  @override
  State<MapView> createState() => _MapViewState();
}

class _MapViewState extends State<MapView> with AutomaticKeepAliveClientMixin {
  AmapController? _controller;

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return Container(
      clipBehavior: Clip.antiAlias,
      decoration: BoxDecoration(borderRadius: BorderRadius.all(Radius.circular(Global.ds(16)))),
      child: Stack(
        alignment: Alignment.topLeft,
        children: [
          Positioned.fill(
            child: Consumer2<RadioControlNotifier, RadioTargetNotifier>(
              builder: (context, radioControlNotifier, radioTargetNotifier, child) => FutureWidget<List<RadioEntity>>(
                future: DBApi.radio.list(),
                loadingDesc: "地图加载中",
                loadingBackgroundColor: Colors.black45,
                doneBuilder: (context, snapshot) => AMap(
                  markers: snapshot.requireData.map<AMapMarker>((e) {
                    if (radioTargetNotifier.target == null) {
                      return _createMarker(e);
                    } else {
                      return _createMarker(e, radioTargetNotifier.target?.id == e.id || context.read<StateNotifier>().localId == e.id);
                    }
                  }).toList(),
                  centerCoordinate: context.read<LocationNotifier>().latLng,
                  onMapClicked: (latLng) {
                    context.read<RadioTargetNotifier>().target = null;
                  },
                  onMapCreated: (controller) async {
                    _controller = controller;
                    radioControlNotifier.removeListener(_listener);
                    RadioEntity? localRadio = await DBApi.radio.localRadio(context.read<StateNotifier>().localId);
                    if (localRadio != null && radioTargetNotifier.target != null) {
                      await controller.addPolyline(PolylineOption(
                        coordinateList: [localRadio.latLng, radioTargetNotifier.target!.latLng],
                        width: Global.ds(5),
                        strokeColor: ColorUtil.color("#FFC069"),
                        lineCapType: LineCapType.Round,
                        lineJoinType: LineJoinType.Round,
                        dashType: DashType.Circle,
                      ));
                    }
                    await controller.showMyLocation(MyLocationOption(show: true, myLocationType: MyLocationType.Follow, interval: const Duration(seconds: 10)));
                    radioControlNotifier.addListener(_listener);
                  },
                ),
              ),
            ),
          ),
          Container(
            margin: EdgeInsets.all(Global.ds(20)),
            padding: EdgeInsets.all(Global.ds(20)),
            clipBehavior: Clip.antiAlias,
            decoration: BoxDecoration(borderRadius: BorderRadius.circular(Global.ds(16)), color: Colors.black54),
            child: DefaultTextStyle(
              maxLines: 1,
              softWrap: false,
              style: TextStyle(fontSize: Global.ds(14), color: Colors.white, height: 1.5),
              child: Consumer<LocationNotifier>(
                builder: (context, notifier, child) {
                  if (notifier.latLng != null) {
                    _controller?.setCenterCoordinate(notifier.latLng!);
                    DBApi.radio.select(context.read<StateNotifier>().localId).then((value) {
                      if (value != null) {
                        value.lat = notifier.latLng!.latitude.toString();
                        value.lng = notifier.latLng!.longitude.toString();
                        DBApi.radio.update(value);
                      }
                    });
                  }
                  return Column(
                    mainAxisSize: MainAxisSize.min,
                    mainAxisAlignment: MainAxisAlignment.center,
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Row(
                        mainAxisSize: MainAxisSize.min,
                        children: [
                          ImageUtil.icon("static/images/icon/2.png", size: Global.ds(16), color: Colors.white),
                          VerticalDivider(width: Global.ds(2), color: Colors.transparent),
                          const Text("GPS:"),
                        ],
                      ),
                      Text("${notifier.latLng?.longitude}"),
                      Text("${notifier.latLng?.latitude}"),
                    ],
                  );
                },
              ),
            ),
          ),
        ],
      ),
    );
  }

  void _listener() => setState(() {});

  AMapMarker _createMarker(RadioEntity entity, [bool active = false]) {
    int? localId = context.read<StateNotifier>().localId;
    bool self = localId == entity.id;
    return AMapMarker(
      id: entity.id,
      anchorU: 1,
      anchorV: 0,
      coordinate: entity.latLng,
      data: entity.toString(),
      onTap: (iMarker, object) async {
        if (object.isNotEmpty) {
          RadioTargetNotifier notifier = context.read<RadioTargetNotifier>();
          Map<String, dynamic> data = jsonDecode(jsonDecode(object)['data']);
          RadioEntity radio = RadioEntity.fromJson(data);
          if (localId != radio.id && notifier.target?.id != radio.id) notifier.target = radio;
        }
      },
      widget: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          SizedBox(
            width: Global.ds(74),
            height: Global.ds(74),
            child: Stack(
              children: [
                Positioned.fill(
                  child: Icon(
                    active
                        ? IconFont.marker0
                        : self
                            ? IconFont.marker1
                            : IconFont.marker2,
                    size: Global.ds(74),
                  ),
                ),
                Positioned(
                  left: Global.ds(18),
                  right: Global.ds(22),
                  bottom: Global.ds(6),
                  child: Text(
                    entity.id.toString(),
                    textAlign: TextAlign.center,
                    overflow: TextOverflow.clip,
                    style: TextStyle(fontSize: Global.ds(14), color: (active) || self ? ColorUtil.color("#101C27") : ColorUtil.color("#07E2D7"), height: 1),
                  ),
                ),
              ],
            ),
          ),
          Container(
            clipBehavior: Clip.antiAlias,
            padding: EdgeInsets.symmetric(horizontal: Global.ds(8), vertical: Global.ds(4)),
            margin: EdgeInsets.only(top: Global.ds(2), right: Global.ds(6)),
            decoration: BoxDecoration(
              color: ColorUtil.color(self ? "#101C27" : "#07E2D7"),
              borderRadius: BorderRadius.circular(Global.ds(8)),
              border: active ? Border.all(color: ColorUtil.color("#FFC069")) : null,
            ),
            child: Text(
              entity.name.isNotEmpty ? entity.name : '[名称]',
              style: TextStyle(color: ColorUtil.color(self ? "#07E2D7" : "#3D3D3D"), fontSize: Global.ds(12)),
            ),
          ),
        ],
      ),
    );
  }

  @override
  bool get wantKeepAlive => true;
}

class RadioList extends StatefulWidget {
  const RadioList({super.key});

  @override
  State<RadioList> createState() => _RadioListState();
}

class _RadioListState extends State<RadioList> {
  @override
  Widget build(BuildContext context) => Column(
        crossAxisAlignment: CrossAxisAlignment.stretch,
        children: [
          Container(
            height: Global.ds(50),
            alignment: Alignment.centerLeft,
            padding: EdgeInsets.symmetric(horizontal: Global.ds(20)),
            child: Text("台站列表", style: TextStyle(fontSize: Global.ds(18), fontWeight: FontWeight.w700, color: ColorUtil.color("#2CA6E0"))),
          ),
          Flexible(
            child: Consumer<RadioControlNotifier>(
              builder: (context, radioControlNotifier, child) => FutureWidget<List<RadioEntity>>(
                future: DBApi.radio.list(),
                loadingDesc: "正在读取台站列表",
                doneBuilder: (context, snapshot) => CustomTable<RadioEntity>(
                  data: snapshot.requireData,
                  fields: const [Text("台站ID"), Text("台站名称"), Text("操作")],
                  shrinkWrap: true,
                  headSize: Global.ds(50),
                  itemSize: Global.ds(60),
                  hoverColor: ColorUtil.color("#46E5CB").withOpacity(.5),
                  headColor: ColorUtil.color("#1A263D"),
                  itemBorder: Border(bottom: BorderSide(color: ColorUtil.color("#1A263D"))),
                  headTextStyle: TextStyle(fontSize: Global.ds(16), color: ColorUtil.color("#036EB7"), overflow: TextOverflow.ellipsis),
                  itemTextStyle: TextStyle(fontSize: Global.ds(18), color: ColorUtil.color("#2CA6E0"), overflow: TextOverflow.ellipsis),
                  itemBuilder: (context, index, data) => [
                    Text("ID-${data.id}${data.id == context.read<StateNotifier>().localId ? '(本机)' : ''}"),
                    Text(data.name),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        IconButton(
                          onPressed: () => _openDrawer('编辑台站设置', entity: data),
                          icon: ImageUtil.icon("static/images/icon/5.png"),
                          style: IconButton.styleFrom(iconSize: Global.ds(24), foregroundColor: ColorUtil.color("#66FFFB")),
                        ),
                        VerticalDivider(width: Global.ds(10), color: Colors.transparent),
                        IconButton(
                          onPressed: () => ModalUtil.confirm(content: "删除后不可以恢复，确定要删除吗？").then((value) {
                            if (value == true) {
                              radioControlNotifier.deleteRadio(data.id).then((value) {
                                setState(() {});
                                ToastUtil.success("台站删除成功");
                              });
                            }
                          }),
                          icon: ImageUtil.icon("static/images/icon/6.png"),
                          style: IconButton.styleFrom(iconSize: Global.ds(24), fixedSize: Size.fromHeight(Global.ds(60)), foregroundColor: ColorUtil.color("#D95348")),
                        ),
                      ],
                    ),
                  ],
                ),
              ),
            ),
          ),
          Padding(
            padding: EdgeInsets.all(Global.ds(20)),
            child: FutureWidget<RadioEntity?>(
              future: DBApi.radio.localRadio(context.read<StateNotifier>().localId),
              doneBuilder: (context, snapshot) => snapshot.data == null
                  ? TextButton(
                      onPressed: () => _openDrawer('初始化台站设置', initLocal: true),
                      style: TextButton.styleFrom(
                        textStyle: TextStyle(fontSize: Global.ds(18)),
                        fixedSize: Size.fromHeight(Global.ds(40)),
                        foregroundColor: ColorUtil.color("#036EB7"),
                        backgroundColor: ColorUtil.color("#46E5CB"),
                        shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(Global.ds(20))),
                      ),
                      child: const Text("初始化台站设置"),
                    )
                  : IconButton(
                      onPressed: () => _openDrawer('创建新台站'),
                      icon: ImageUtil.icon("static/images/icon/plus.png"),
                      style: IconButton.styleFrom(
                        iconSize: Global.ds(24),
                        fixedSize: Size.fromHeight(Global.ds(40)),
                        foregroundColor: ColorUtil.color("#036EB7"),
                        backgroundColor: ColorUtil.color("#46E5CB"),
                        shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(Global.ds(20))),
                      ),
                    ),
            ),
          ),
        ],
      );

  void _openDrawer(String title, {RadioEntity? entity, bool initLocal = false}) => ModalUtil.drawer<RadioEntity>(
        context: context,
        title: title,
        width: Global.ds(620),
        radius: Global.ds(16),
        child: RadioSetting(entity: entity, initLocal: initLocal, onSubmit: (entity) => Navigator.pop(context, entity)),
      ).then((entity) {
        if (entity != null) setState(() {});
      });
}

class RadioSetting extends StatefulWidget {
  final RadioEntity? entity;
  final bool initLocal;
  final void Function(RadioEntity entity)? onSubmit;

  const RadioSetting({super.key, this.entity, this.initLocal = false, this.onSubmit});

  @override
  State<RadioSetting> createState() => _RadioSettingState();
}

class _RadioSettingState extends State<RadioSetting> {
  int? id;
  String? name;
  int? type;
  int? antenna;
  String? lat;
  String? lng;

  @override
  void initState() {
    WidgetsBinding.instance.addPostFrameCallback((timeStamp) => _initForm());
    super.initState();
  }

  @override
  Widget build(BuildContext context) => Padding(
        padding: EdgeInsets.all(Global.ds(20)),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: [
            Row(
              children: [
                SizedBox(
                  width: Global.ds(86),
                  child: Text("台站ID：", style: TextStyle(fontSize: Global.ds(16), height: 1, color: ColorUtil.color("#FAFAFA")), textAlign: TextAlign.right),
                ),
                Expanded(
                  child: Container(
                    height: Global.ds(40),
                    alignment: Alignment.centerLeft,
                    padding: EdgeInsets.symmetric(horizontal: Global.ds(15)),
                    decoration: BoxDecoration(
                      color: ColorUtil.color("#366485"),
                      border: Border.all(color: ColorUtil.color("#3B99CC")),
                      borderRadius: BorderRadius.circular(Global.ds(20)),
                    ),
                    child: InputField(
                      key: UniqueKey(),
                      initialValue: "${id ?? ''}",
                      hintText: "请输入台站ID",
                      disabled: id != null,
                      keyboardType: TextInputType.number,
                      textStyle: TextStyle(fontSize: Global.ds(18), height: 1, color: ColorUtil.color("#ABDBF3")),
                      hintStyle: TextStyle(color: ColorUtil.color("#ABDBF3").withOpacity(.5)),
                      onChanged: (controller, focusNode, value) => id = int.tryParse(value),
                    ),
                  ),
                ),
              ],
            ),
            Divider(height: Global.ds(30), color: Colors.transparent),
            Row(
              children: [
                SizedBox(
                  width: Global.ds(86),
                  child: Text("台站名称：", style: TextStyle(fontSize: Global.ds(16), height: 1, color: ColorUtil.color("#FAFAFA")), textAlign: TextAlign.right),
                ),
                Expanded(
                  child: Container(
                    height: Global.ds(40),
                    alignment: Alignment.centerLeft,
                    padding: EdgeInsets.symmetric(horizontal: Global.ds(15)),
                    decoration: BoxDecoration(
                      color: ColorUtil.color("#366485"),
                      border: Border.all(color: ColorUtil.color("#3B99CC")),
                      borderRadius: BorderRadius.circular(Global.ds(20)),
                    ),
                    child: InputField(
                      key: UniqueKey(),
                      initialValue: name ?? '',
                      hintText: "请输入台站名称",
                      textStyle: TextStyle(fontSize: Global.ds(18), height: 1, color: ColorUtil.color("#ABDBF3")),
                      hintStyle: TextStyle(color: ColorUtil.color("#ABDBF3").withOpacity(.5)),
                      onChanged: (controller, focusNode, value) => name = value.trim(),
                    ),
                  ),
                ),
              ],
            ),
            Divider(height: Global.ds(30), color: Colors.transparent),
            Row(
              children: [
                SizedBox(
                  width: Global.ds(86),
                  child: Text("台站类型：", style: TextStyle(fontSize: Global.ds(16), height: 1, color: ColorUtil.color("#FAFAFA")), textAlign: TextAlign.right),
                ),
                Expanded(
                  child: Container(
                    height: Global.ds(40),
                    alignment: Alignment.centerLeft,
                    padding: EdgeInsets.symmetric(horizontal: Global.ds(15)),
                    decoration: BoxDecoration(
                      color: ColorUtil.color("#366485"),
                      border: Border.all(color: ColorUtil.color("#3B99CC")),
                      borderRadius: BorderRadius.circular(Global.ds(20)),
                    ),
                    child: Dropdown<int>(
                      key: UniqueKey(),
                      options: RadioType.values.map((e) => DropdownMenuItem<int>(value: e.index, child: Text(e.name))).toList(),
                      initialValue: type,
                      hintText: "请选择台站类型",
                      fontSize: Global.ds(18),
                      fontColor: ColorUtil.color("#ABDBF3"),
                      dropdownColor: ColorUtil.color("#1A263D"),
                      onChanged: (value) => type = value,
                    ),
                  ),
                ),
              ],
            ),
            Divider(height: Global.ds(30), color: Colors.transparent),
            Row(
              children: [
                SizedBox(
                  width: Global.ds(86),
                  child: Text("天线类型：", style: TextStyle(fontSize: Global.ds(16), height: 1, color: ColorUtil.color("#FAFAFA")), textAlign: TextAlign.right),
                ),
                Expanded(
                  child: Container(
                    height: Global.ds(40),
                    alignment: Alignment.centerLeft,
                    padding: EdgeInsets.symmetric(horizontal: Global.ds(15)),
                    decoration: BoxDecoration(
                      color: ColorUtil.color("#366485"),
                      border: Border.all(color: ColorUtil.color("#3B99CC")),
                      borderRadius: BorderRadius.circular(Global.ds(20)),
                    ),
                    child: Dropdown<int>(
                      key: UniqueKey(),
                      options: AntennaType.values.map((e) => DropdownMenuItem<int>(value: e.index, child: Text(e.name))).toList(),
                      initialValue: antenna,
                      hintText: "请选择天线类型",
                      fontSize: Global.ds(18),
                      fontColor: ColorUtil.color("#ABDBF3"),
                      dropdownColor: ColorUtil.color("#1A263D"),
                      onChanged: (value) => antenna = value,
                    ),
                  ),
                ),
              ],
            ),
            Divider(height: Global.ds(30), color: Colors.transparent),
            Row(
              children: [
                SizedBox(
                  width: Global.ds(86),
                  child: Text("经度：", style: TextStyle(fontSize: Global.ds(16), height: 1, color: ColorUtil.color("#FAFAFA")), textAlign: TextAlign.right),
                ),
                Expanded(
                  child: GestureDetector(
                    onTap: widget.initLocal ? null : _choosePoint,
                    child: Container(
                      height: Global.ds(40),
                      alignment: Alignment.centerLeft,
                      padding: EdgeInsets.symmetric(horizontal: Global.ds(15)),
                      decoration: BoxDecoration(
                        color: ColorUtil.color("#366485"),
                        border: Border.all(color: ColorUtil.color("#3B99CC")),
                        borderRadius: BorderRadius.circular(Global.ds(20)),
                      ),
                      child: lng == null
                          ? Text("点击从地图选择", style: TextStyle(fontSize: Global.ds(18), height: 1, color: ColorUtil.color("#ABDBF3").withOpacity(.5)))
                          : Text(lng!, style: TextStyle(fontSize: Global.ds(18), height: 1, color: ColorUtil.color("#ABDBF3"))),
                    ),
                  ),
                ),
                SizedBox(
                  width: Global.ds(86),
                  child: Text("纬度：", style: TextStyle(fontSize: Global.ds(16), height: 1, color: ColorUtil.color("#FAFAFA")), textAlign: TextAlign.right),
                ),
                Expanded(
                  child: GestureDetector(
                    onTap: widget.initLocal ? null : _choosePoint,
                    child: Container(
                      height: Global.ds(40),
                      alignment: Alignment.centerLeft,
                      padding: EdgeInsets.symmetric(horizontal: Global.ds(15)),
                      decoration: BoxDecoration(
                        color: ColorUtil.color("#366485"),
                        border: Border.all(color: ColorUtil.color("#3B99CC")),
                        borderRadius: BorderRadius.circular(Global.ds(20)),
                      ),
                      child: lat == null
                          ? Text("点击从地图选择", style: TextStyle(fontSize: Global.ds(18), height: 1, color: ColorUtil.color("#ABDBF3").withOpacity(.5)))
                          : Text(lat!, style: TextStyle(fontSize: Global.ds(18), height: 1, color: ColorUtil.color("#ABDBF3"))),
                    ),
                  ),
                ),
              ],
            ),
            const Spacer(),
            Row(mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: [
              TextButton(
                onPressed: _initForm,
                style: TextButton.styleFrom(
                  fixedSize: Size(Global.ds(162), Global.ds(46)),
                  textStyle: TextStyle(fontSize: Global.ds(18), height: 1),
                  shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(Global.ds(23))),
                  foregroundColor: Colors.white,
                  backgroundColor: ColorUtil.color("#D95348"),
                ),
                child: const Text("重置"),
              ),
              TextButton(
                onPressed: () {
                  if (id == null) {
                    ToastUtil.error("请输入台站ID");
                  } else if (id! <= 0 || id! % 1 > 0) {
                    ToastUtil.error("台站ID必须是正整数");
                  } else if (name?.isEmpty ?? true) {
                    ToastUtil.error("请输入台站名称");
                  } else if (type == null) {
                    ToastUtil.error("请选择台站类型");
                  } else if (antenna == null) {
                    ToastUtil.error("请选择天线类型");
                  } else if ((lat?.isEmpty ?? true) || (lng?.isEmpty ?? true)) {
                    ToastUtil.error("请点击地图选择经纬度");
                  } else {
                    RadioEntity entity = RadioEntity(id!, name!, type!, antenna!, lat!, lng!);
                    context.read<RadioControlNotifier>().submitRadio(entity).then((value) {
                      if (value != null) widget.onSubmit?.call(value);
                    });
                  }
                },
                style: TextButton.styleFrom(
                  fixedSize: Size(Global.ds(162), Global.ds(46)),
                  textStyle: TextStyle(fontSize: Global.ds(18), height: 1),
                  shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(Global.ds(23))),
                  foregroundColor: Colors.white,
                  backgroundColor: ColorUtil.color("#2CA6E0"),
                ),
                child: const Text("保存"),
              ),
            ]),
          ],
        ),
      );

  void _initForm() {
    RadioEntity? target = widget.entity;
    id = target?.id;
    name = target?.name;
    type = target?.type;
    antenna = target?.antenna;
    lat = target?.lat;
    lng = target?.lng;
    if (widget.initLocal) {
      id = context.read<StateNotifier>().localId;
      LatLng? latLng = context.read<LocationNotifier>().latLng;
      lat = latLng?.latitude.toString();
      lng = latLng?.longitude.toString();
    }
    setState(() {});
  }

  void _choosePoint() {
    AMap.choosePoint(context).then((value) {
      if (value != null) {
        setState(() {
          lat = Global.toFixed(value.latitude, 5).toString();
          lng = Global.toFixed(value.longitude, 5).toString();
        });
      }
    });
  }
}

class Spectrum extends StatefulWidget {
  const Spectrum({super.key});

  @override
  State<Spectrum> createState() => _SpectrumState();
}

class _SpectrumState extends State<Spectrum> with AutomaticKeepAliveClientMixin {
  final GlobalObjectKey _chartKey = const GlobalObjectKey("chart");
  final List<List<int>> data = [];
  double center = 0;
  int bwIndex = 0;

  @override
  void initState() {
    WSUtil.connect().listener([
      ReceiveMsgListener("pp", (response) {
        if (response['channel'] == 0) {
          List<int> bytes = response['msg'].split(",").map<int>((e) => int.tryParse(e.toString()) ?? 0).toList();
          if (bytes.length == 256) {
            data.add(bytes);
            _chartKey.currentState?.setState(() {});
          }
        }
        return false;
      })
    ]);
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return Column(
      crossAxisAlignment: CrossAxisAlignment.stretch,
      children: [
        Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            Text("中心频率：", style: TextStyle(fontSize: Global.ds(16), color: ColorUtil.color("#FAFAFA"))),
            Expanded(
              child: Container(
                height: Global.ds(40),
                alignment: Alignment.centerLeft,
                padding: EdgeInsets.symmetric(horizontal: Global.ds(15)),
                decoration: BoxDecoration(
                  color: ColorUtil.color("#366485"),
                  border: Border.all(color: ColorUtil.color("#3B99CC")),
                  borderRadius: BorderRadius.circular(Global.ds(20)),
                ),
                child: InputField(
                  key: UniqueKey(),
                  initialValue: "$center",
                  hintText: "请输入中心频率",
                  keyboardType: const TextInputType.numberWithOptions(decimal: true),
                  textStyle: TextStyle(fontSize: Global.ds(18), height: 1, color: ColorUtil.color("#ABDBF3")),
                  hintStyle: TextStyle(color: ColorUtil.color("#ABDBF3").withOpacity(.5)),
                  onChanged: (controller, focusNode, value) => center = double.tryParse(value) ?? 0,
                ),
              ),
            ),
            VerticalDivider(width: Global.ds(10), color: Colors.transparent),
            Text("MHz", style: TextStyle(fontSize: Global.ds(14), color: ColorUtil.color("#9E9E9E"))),
            VerticalDivider(width: Global.ds(80), color: Colors.transparent),
            Text("频率分辨率：", style: TextStyle(fontSize: Global.ds(16), color: ColorUtil.color("#FAFAFA"))),
            Expanded(
              child: Container(
                height: Global.ds(40),
                alignment: Alignment.centerLeft,
                padding: EdgeInsets.symmetric(horizontal: Global.ds(15)),
                decoration: BoxDecoration(
                  color: ColorUtil.color("#366485"),
                  border: Border.all(color: ColorUtil.color("#3B99CC")),
                  borderRadius: BorderRadius.circular(Global.ds(20)),
                ),
                child: Dropdown<int>(
                  key: UniqueKey(),
                  options: RBWType.values.map((e) => DropdownMenuItem<int>(value: e.index, child: Text(e.name))).toList(),
                  initialValue: bwIndex,
                  hintText: "请选择频率分辨率",
                  fontSize: Global.ds(18),
                  fontColor: ColorUtil.color("#ABDBF3"),
                  dropdownColor: ColorUtil.color("#1A263D"),
                  onChanged: (value) => bwIndex = value ?? 0,
                ),
              ),
            ),
            VerticalDivider(width: Global.ds(80), color: Colors.transparent),
            TextButton(
              onPressed: () => ApiUtil().spectrum({"bw": bwIndex, "freq": center * 1000000}).then((value) => setState(() {})),
              style: TextButton.styleFrom(
                fixedSize: Size(Global.ds(160), Global.ds(40)),
                textStyle: TextStyle(fontSize: Global.ds(18)),
                foregroundColor: Colors.white,
                backgroundColor: ColorUtil.color("#2CA6E0"),
                shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(Global.ds(20))),
              ),
              child: const Text("确定"),
            ),
          ],
        ),
        Divider(height: Global.ds(20), color: Colors.transparent),
        Expanded(
          child: Container(
            clipBehavior: Clip.antiAlias,
            padding: EdgeInsets.all(Global.ds(20)),
            decoration: BoxDecoration(color: ColorUtil.color("#1A3959"), borderRadius: BorderRadius.circular(Global.ds(16))),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.stretch,
              children: [
                DefaultTextStyle(
                  style: TextStyle(fontSize: Global.ds(18), color: ColorUtil.color("#3B99CC")),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                    children: [Text("FR:${center}MHz"), Text("BW:${Global.toFixed(RBWType.values[bwIndex].bw / 1000000, 3)}MHz"), Text("RBW:${RBWType.values[bwIndex].name}")],
                  ),
                ),
                Expanded(
                  child: Container(
                    clipBehavior: Clip.antiAlias,
                    margin: EdgeInsets.symmetric(vertical: Global.ds(20)),
                    padding: EdgeInsets.only(left: Global.ds(10), top: Global.ds(20), right: Global.ds(20), bottom: Global.ds(20)),
                    decoration: BoxDecoration(color: ColorUtil.color("#1A263D"), borderRadius: BorderRadius.circular(Global.ds(16))),
                    child: StatefulBuilder(key: _chartKey, builder: (context, stateSetter) => Chart(data: data)),
                  ),
                ),
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                  children: [
                    IconButton(
                      onPressed: () {},
                      color: Colors.white,
                      iconSize: Global.ds(35),
                      padding: EdgeInsets.zero,
                      icon: ImageUtil.icon("static/images/icon/speaker.png", size: Global.ds(35), color: Colors.white),
                      constraints: const BoxConstraints(minHeight: 0, minWidth: 0),
                      style: IconButton.styleFrom(
                        fixedSize: Size(Global.ds(160), Global.ds(40)),
                        backgroundColor: ColorUtil.color("#FFC069"),
                        shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(Global.ds(20))),
                      ),
                    ),
                    TextButton(
                      onPressed: () {},
                      style: TextButton.styleFrom(
                        textStyle: TextStyle(fontSize: Global.ds(18)),
                        fixedSize: Size(Global.ds(160), Global.ds(40)),
                        foregroundColor: Colors.white,
                        backgroundColor: ColorUtil.color("#2CA6E0"),
                        shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(Global.ds(20))),
                      ),
                      child: const Text("保存"),
                    ),
                  ],
                ),
              ],
            ),
          ),
        ),
      ],
    );
  }

  @override
  bool get wantKeepAlive => true;
}

class Setting extends StatefulWidget {
  const Setting({super.key});

  @override
  State<Setting> createState() => _SettingState();
}

class _SettingState extends State<Setting> {
  @override
  Widget build(BuildContext context) => SingleChildScrollView(
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: [
            _item1,
            Divider(height: 1, thickness: 1, color: ColorUtil.color("#1A263D")),
            _item3,
            Divider(height: 1, thickness: 1, color: ColorUtil.color("#1A263D")),
            _item4,
            Divider(height: 1, thickness: 1, color: ColorUtil.color("#1A263D")),
            _item5,
          ],
        ),
      );

  Widget get _item1 => InkWell(
        onTap: () => ModalUtil.drawer<RadioEntity>(
          context: context,
          title: "禁用频率表编辑",
          width: Global.ds(620),
          radius: Global.ds(16),
          child: const DisabledMHz(),
        ),
        child: Ink(
          height: Global.ds(80),
          padding: EdgeInsets.symmetric(horizontal: Global.ds(20)),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Text("禁用频率表编辑", style: TextStyle(fontSize: Global.ds(18), fontWeight: FontWeight.w700, color: ColorUtil.color("#74C8CE"))),
              Icon(Icons.arrow_forward_ios, size: Global.ds(18), color: ColorUtil.color("#2CA6E0")),
            ],
          ),
        ),
      );

  Widget get _item2 => InkWell(
        onTap: () => ModalUtil.drawer<RadioEntity>(
          context: context,
          title: "滤波器波段选择",
          width: Global.ds(620),
          radius: Global.ds(16),
          child: StatefulBuilder(builder: (context, stateSetter) {
            int? value = StorageUtil.get<int>("FilterBand");
            return Column(
              crossAxisAlignment: CrossAxisAlignment.stretch,
              children: [
                Padding(
                  padding: EdgeInsets.all(Global.ds(20)),
                  child: Text(
                    value == null ? "当前未选择波段" : "当前选择波段：${filterBand[value - 1]}",
                    style: TextStyle(fontSize: Global.ds(18), color: ColorUtil.color("#2CA6E0")),
                  ),
                ),
                Expanded(
                  child: CustomTable<String>(
                    data: filterBand,
                    fields: const [Text("序号"), Text("波段"), Text("操作")],
                    shrinkWrap: true,
                    headSize: Global.ds(50),
                    itemSize: Global.ds(60),
                    hoverColor: ColorUtil.color("#46E5CB").withOpacity(.5),
                    headColor: ColorUtil.color("#1A263D"),
                    itemBorder: Border(bottom: BorderSide(color: ColorUtil.color("#1A263D"))),
                    headTextStyle: TextStyle(fontSize: Global.ds(16), color: ColorUtil.color("#036EB7"), overflow: TextOverflow.ellipsis),
                    itemTextStyle: TextStyle(fontSize: Global.ds(18), color: ColorUtil.color("#2CA6E0"), overflow: TextOverflow.ellipsis),
                    itemBuilder: (context, index, data) => [
                      Text("${index + 1}"),
                      Text(data),
                      Container(
                        width: Global.ds(24),
                        height: Global.ds(24),
                        alignment: Alignment.center,
                        clipBehavior: Clip.antiAlias,
                        decoration: BoxDecoration(color: ColorUtil.color("#D8D8D8"), borderRadius: BorderRadius.circular(Global.ds(12))),
                        child: index + 1 == value
                            ? Container(
                                width: Global.ds(16),
                                height: Global.ds(16),
                                clipBehavior: Clip.antiAlias,
                                decoration: BoxDecoration(color: ColorUtil.color("#2CA6E0"), borderRadius: BorderRadius.circular(Global.ds(8))),
                              )
                            : null,
                      ),
                    ],
                    onTapItem: (index, data) => stateSetter(() => StorageUtil.set<int>("FilterBand", index + 1)),
                  ),
                ),
              ],
            );
          }),
        ),
        child: Ink(
          height: Global.ds(80),
          padding: EdgeInsets.symmetric(horizontal: Global.ds(20)),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Text("滤波器波段选择", style: TextStyle(fontSize: Global.ds(18), fontWeight: FontWeight.w700, color: ColorUtil.color("#74C8CE"))),
              Icon(Icons.arrow_forward_ios, size: Global.ds(18), color: ColorUtil.color("#2CA6E0")),
            ],
          ),
        ),
      );

  Widget get _item3 => Ink(
        height: Global.ds(80),
        padding: EdgeInsets.symmetric(horizontal: Global.ds(20)),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            Text("射频前端衰减控制", style: TextStyle(fontSize: Global.ds(18), fontWeight: FontWeight.w700, color: ColorUtil.color("#74C8CE"))),
            Container(
              width: Global.ds(80),
              height: Global.ds(40),
              alignment: Alignment.centerRight,
              child: Dropdown<int>(
                key: UniqueKey(),
                options: filterAttenuation.asMap().keys.map((i) => DropdownMenuItem<int>(value: i, child: Text(filterAttenuation[i]))).toList(),
                initialValue: StorageUtil.get<int>("FilterAttenuation") ?? 0,
                hintText: "请选择",
                fontSize: Global.ds(18),
                fontColor: ColorUtil.color("#ABDBF3"),
                dropdownColor: ColorUtil.color("#1A263D"),
                icon: Icon(Icons.keyboard_arrow_down, color: ColorUtil.color("#2CA6E0")),
                onChanged: (value) {
                  StorageUtil.set<int>("FilterAttenuation", value!);
                  ApiUtil().decay(value);
                },
              ),
            ),
          ],
        ),
      );

  Widget get _item4 {
    bool unfold = false, added = false;
    return StatefulBuilder(
      builder: (context, stateSetter) => Column(crossAxisAlignment: CrossAxisAlignment.stretch, children: [
        InkWell(
          onTap: () => stateSetter(() => unfold = !unfold),
          child: Ink(
            height: Global.ds(80),
            color: ColorUtil.color("#1A3959"),
            padding: EdgeInsets.symmetric(horizontal: Global.ds(20)),
            child: Center(
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Text("带宽设置", style: TextStyle(fontSize: Global.ds(18), fontWeight: FontWeight.w700, color: ColorUtil.color("#74C8CE"))),
                  AnimatedRotation(
                    key: const ValueKey<String>("AnimatedRotation-BW"),
                    turns: unfold ? 0.25 : 0,
                    curve: Curves.fastOutSlowIn,
                    filterQuality: FilterQuality.high,
                    duration: const Duration(milliseconds: 300),
                    child: Icon(Icons.arrow_forward_ios, size: Global.ds(18), color: ColorUtil.color("#2CA6E0")),
                  ),
                ],
              ),
            ),
          ),
        ),
        AnimatedSwitcher(
          key: const ValueKey<String>("AnimatedSwitcher-BW"),
          switchInCurve: Curves.fastOutSlowIn,
          switchOutCurve: Curves.fastOutSlowIn,
          duration: const Duration(milliseconds: 300),
          transitionBuilder: (child, animation) => SizeTransition(sizeFactor: animation, child: child),
          child: unfold
              ? Container(
                  alignment: AlignmentDirectional.centerStart,
                  color: ColorUtil.color("#1A263D"),
                  padding: EdgeInsets.only(left: Global.ds(50), top: Global.ds(20), right: Global.ds(20), bottom: Global.ds(20)),
                  child: StatefulBuilder(
                    builder: (context, itemStateSetter) {
                      List<double> bw = (StorageUtil.get<String>("BW") ?? '').split(',').map((e) => double.tryParse(e)).toList().whereNotNull();
                      List<Widget> widgets = bw
                          .asMap()
                          .keys
                          .map<Widget>((i) => Container(
                                height: Global.ds(40),
                                decoration: BoxDecoration(
                                  color: ColorUtil.color("#2B526F"),
                                  borderRadius: BorderRadius.circular(Global.ds(20)),
                                ),
                                child: Row(
                                  mainAxisSize: MainAxisSize.min,
                                  mainAxisAlignment: MainAxisAlignment.center,
                                  children: [
                                    VerticalDivider(width: Global.ds(15), color: Colors.transparent),
                                    Text("${bw[i]}", style: TextStyle(fontSize: Global.ds(18), color: Colors.white)),
                                    IconButton(
                                      onPressed: () {
                                        itemStateSetter(() {
                                          bw.removeAt(i);
                                          StorageUtil.set<String>("BW", bw.join(','));
                                        });
                                        ToastUtil.success("删除成功");
                                      },
                                      icon: ImageUtil.icon("static/images/icon/close.png"),
                                      style: IconButton.styleFrom(iconSize: Global.ds(20), foregroundColor: ColorUtil.color("#FBD580")),
                                    ),
                                  ],
                                ),
                              ))
                          .toList();
                      widgets.add(StatefulBuilder(builder: (context, addStateSetter) {
                        if (added) {
                          return Container(
                            width: Global.ds(160),
                            height: Global.ds(40),
                            alignment: Alignment.centerLeft,
                            padding: EdgeInsets.symmetric(horizontal: Global.ds(15)),
                            decoration: BoxDecoration(
                              color: ColorUtil.color("#366485"),
                              borderRadius: BorderRadius.circular(Global.ds(20)),
                            ),
                            child: InputField(
                              key: UniqueKey(),
                              hintText: "输入带宽",
                              autofocus: true,
                              keyboardType: const TextInputType.numberWithOptions(decimal: true),
                              textStyle: TextStyle(fontSize: Global.ds(18), height: 1, color: Colors.white),
                              hintStyle: TextStyle(color: Colors.white.withOpacity(.5)),
                              suffix: const Text("MHz"),
                              onBlur: (controller, focusNode, value) => addStateSetter(() => added = false),
                              onSubmitted: (controller, focusNode, value) {
                                double? val = double.tryParse(value);
                                if (val != null) {
                                  val = Global.toFixed(val, 3);
                                  if (bw.contains(val)) {
                                    ToastUtil.error("输入的值已存在");
                                  } else {
                                    bw.add(val);
                                    itemStateSetter(() {
                                      StorageUtil.set<String>("BW", bw.join(','));
                                      added = false;
                                    });
                                    ToastUtil.success("添加成功");
                                  }
                                } else {
                                  ToastUtil.error("输入的值有误");
                                }
                              },
                            ),
                          );
                        } else {
                          return IconButton(
                            onPressed: () => addStateSetter(() => added = true),
                            icon: ImageUtil.icon("static/images/icon/plus.png"),
                            style: IconButton.styleFrom(
                              iconSize: Global.ds(24),
                              fixedSize: Size(Global.ds(120), Global.ds(40)),
                              foregroundColor: ColorUtil.color("#036EB7"),
                              backgroundColor: ColorUtil.color("#46E5CB"),
                              shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(Global.ds(20))),
                            ),
                          );
                        }
                      }));
                      return Wrap(spacing: Global.ds(20), runSpacing: Global.ds(20), children: widgets);
                    },
                  ),
                )
              : null,
        ),
      ]),
    );
  }

  Widget get _item5 => InkWell(
        onTap: () => Navigator.of(context).push(MaterialPageRoute(builder: (context) => const LogConsole())),
        child: Ink(
          height: Global.ds(80),
          padding: EdgeInsets.symmetric(horizontal: Global.ds(20)),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Text("调试日志", style: TextStyle(fontSize: Global.ds(18), fontWeight: FontWeight.w700, color: ColorUtil.color("#74C8CE"))),
              Icon(Icons.arrow_forward_ios, size: Global.ds(18), color: ColorUtil.color("#2CA6E0")),
            ],
          ),
        ),
      );
}

class DataRW extends StatefulWidget {
  const DataRW({super.key});

  @override
  State<DataRW> createState() => _DataRWState();
}

class _DataRWState extends State<DataRW> {
  final GlobalObjectKey _msgKey = const GlobalObjectKey("msg");
  final List<String> msg = [];
  String? readAddress, writeAddress, data1, data2;
  double? sendMHz, receiveMHz;
  RadioState? radioState;
  PowerType? powerType;

  @override
  void initState() {
    WSUtil.connect().listener([
      ReceiveMsgListener("data", (response) {
        msg.insert(0, "接收消息: ${response['msg']}");
        _msgKey.currentState?.setState(() {});
        return false;
      })
    ]);
    super.initState();
  }

  @override
  Widget build(BuildContext context) => Column(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        crossAxisAlignment: CrossAxisAlignment.stretch,
        children: [
          Expanded(
            child: Padding(
              padding: EdgeInsets.symmetric(horizontal: Global.ds(20), vertical: Global.ds(10)),
              child: Column(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                crossAxisAlignment: CrossAxisAlignment.stretch,
                children: _widgets,
              ),
            ),
          ),
          StatefulBuilder(
            key: _msgKey,
            builder: (context, stateSetter) => DefaultTextStyle(
              style: TextStyle(fontSize: Global.ds(18), color: ColorUtil.color("#E8E8E8")),
              child: Container(
                height: Global.ds(160),
                color: ColorUtil.color("#1A263D"),
                alignment: Alignment.topCenter,
                child: ListView.builder(
                  shrinkWrap: true,
                  itemCount: msg.length,
                  itemExtent: Global.ds(36),
                  padding: EdgeInsets.symmetric(horizontal: Global.ds(40), vertical: Global.ds(20)),
                  itemBuilder: (context, index) => Container(height: Global.ds(36), alignment: Alignment.centerLeft, child: Text(msg[index])),
                ),
              ),
            ),
          ),
        ],
      );

  List<Widget> get _widgets {
    List<Widget> list = [
      Text("读写值", style: TextStyle(fontSize: Global.ds(18), fontWeight: FontWeight.w700, color: ColorUtil.color("#3B99CC"))),
      Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Container(
            width: Global.ds(86),
            height: Global.ds(40),
            alignment: Alignment.centerRight,
            child: Text("读取地址：", style: TextStyle(fontSize: Global.ds(16), color: ColorUtil.color("#FAFAFA")), textAlign: TextAlign.right),
          ),
          Expanded(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Container(
                  height: Global.ds(40),
                  alignment: Alignment.centerLeft,
                  padding: EdgeInsets.symmetric(horizontal: Global.ds(15)),
                  decoration: BoxDecoration(
                    color: ColorUtil.color("#366485"),
                    border: Border.all(color: ColorUtil.color("#3B99CC")),
                    borderRadius: BorderRadius.circular(Global.ds(20)),
                  ),
                  child: InputField(
                    key: UniqueKey(),
                    initialValue: readAddress ?? '',
                    hintText: "输入地址（10进制）",
                    keyboardType: TextInputType.number,
                    textStyle: TextStyle(fontSize: Global.ds(18), height: 1, color: ColorUtil.color("#ABDBF3")),
                    hintStyle: TextStyle(color: ColorUtil.color("#ABDBF3").withOpacity(.5)),
                    onChanged: (controller, focusNode, value) => readAddress = value.trim(),
                  ),
                ),
                Text("（10进制）", style: TextStyle(fontSize: Global.ds(16), color: ColorUtil.color("#3B99CC"))),
              ],
            ),
          ),
          VerticalDivider(width: Global.ds(20), color: Colors.transparent),
          TextButton(
            onPressed: () {
              if (readAddress?.isEmpty ?? true) {
                ToastUtil.failure("请输入读取地址");
              } else {
                int? addr = int.tryParse(readAddress!);
                if (addr == null) {
                  ToastUtil.failure("读取地址无效");
                } else {
                  ApiUtil().read(addr).then((value) {
                    msg.insert(0, "读取地址: $addr, 结果: $value");
                    _msgKey.currentState?.setState(() {});
                  }).catchError((error) {
                    ToastUtil.error(error.toString());
                  });
                }
              }
            },
            style: TextButton.styleFrom(
              fixedSize: Size(Global.ds(100), Global.ds(40)),
              textStyle: TextStyle(fontSize: Global.ds(18)),
              foregroundColor: Colors.white,
              backgroundColor: ColorUtil.color("#2CA6E0"),
              shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(Global.ds(20))),
            ),
            child: const Text("GO"),
          ),
        ],
      ),
      Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Container(
            width: Global.ds(86),
            height: Global.ds(40),
            alignment: Alignment.centerRight,
            child: Text("写入地址：", style: TextStyle(fontSize: Global.ds(16), color: ColorUtil.color("#FAFAFA")), textAlign: TextAlign.right),
          ),
          Expanded(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Container(
                  height: Global.ds(40),
                  alignment: Alignment.centerLeft,
                  padding: EdgeInsets.symmetric(horizontal: Global.ds(15)),
                  decoration: BoxDecoration(
                    color: ColorUtil.color("#366485"),
                    border: Border.all(color: ColorUtil.color("#3B99CC")),
                    borderRadius: BorderRadius.circular(Global.ds(20)),
                  ),
                  child: InputField(
                    key: UniqueKey(),
                    initialValue: writeAddress ?? '',
                    hintText: "输入地址",
                    keyboardType: TextInputType.number,
                    textStyle: TextStyle(fontSize: Global.ds(18), height: 1, color: ColorUtil.color("#ABDBF3")),
                    hintStyle: TextStyle(color: ColorUtil.color("#ABDBF3").withOpacity(.5)),
                    onChanged: (controller, focusNode, value) => writeAddress = value.trim(),
                  ),
                ),
                Text("（10进制）", style: TextStyle(fontSize: Global.ds(16), color: ColorUtil.color("#3B99CC"))),
              ],
            ),
          ),
          VerticalDivider(width: Global.ds(20), color: Colors.transparent),
          Container(
            width: Global.ds(86),
            height: Global.ds(40),
            alignment: Alignment.centerRight,
            child: Text("数据：", style: TextStyle(fontSize: Global.ds(16), color: ColorUtil.color("#FAFAFA")), textAlign: TextAlign.right),
          ),
          Expanded(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Container(
                  height: Global.ds(40),
                  alignment: Alignment.centerLeft,
                  padding: EdgeInsets.symmetric(horizontal: Global.ds(15)),
                  decoration: BoxDecoration(
                    color: ColorUtil.color("#366485"),
                    border: Border.all(color: ColorUtil.color("#3B99CC")),
                    borderRadius: BorderRadius.circular(Global.ds(20)),
                  ),
                  child: InputField(
                    key: UniqueKey(),
                    initialValue: data1 ?? '',
                    hintText: "输入数据",
                    keyboardType: TextInputType.number,
                    textStyle: TextStyle(fontSize: Global.ds(18), height: 1, color: ColorUtil.color("#ABDBF3")),
                    hintStyle: TextStyle(color: ColorUtil.color("#ABDBF3").withOpacity(.5)),
                    onChanged: (controller, focusNode, value) => data1 = value.trim(),
                  ),
                ),
                Text("（10进制）", style: TextStyle(fontSize: Global.ds(16), color: ColorUtil.color("#3B99CC"))),
              ],
            ),
          ),
          VerticalDivider(width: Global.ds(20), color: Colors.transparent),
          TextButton(
            onPressed: () {
              if (writeAddress?.isEmpty ?? true) {
                ToastUtil.failure("请输入写入地址");
              } else if (data1?.isEmpty ?? true) {
                ToastUtil.failure("请输入数据");
              } else {
                int? addr = int.tryParse(writeAddress!), data = int.tryParse(data1!);
                if (addr == null) {
                  ToastUtil.failure("写入地址无效");
                } else if (data == null) {
                  ToastUtil.failure("数据无效");
                } else {
                  ApiUtil().write(addr, data).then((value) {
                    msg.insert(0, "写入地址: $addr, 数据: $data");
                    _msgKey.currentState?.setState(() {});
                  }).catchError((error) {
                    ToastUtil.error(error.toString());
                  });
                }
              }
            },
            style: TextButton.styleFrom(
              fixedSize: Size(Global.ds(100), Global.ds(40)),
              textStyle: TextStyle(fontSize: Global.ds(18)),
              foregroundColor: Colors.white,
              backgroundColor: ColorUtil.color("#2CA6E0"),
              shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(Global.ds(20))),
            ),
            child: const Text("GO"),
          ),
        ],
      ),
      Divider(height: 1, thickness: 1, color: ColorUtil.color("#31659B")),
      Text("数传", style: TextStyle(fontSize: Global.ds(18), fontWeight: FontWeight.w700, color: ColorUtil.color("#3B99CC"))),
      Row(
        children: [
          Container(
            width: Global.ds(86),
            height: Global.ds(40),
            alignment: Alignment.centerRight,
            child: Text("传输模式：", style: TextStyle(fontSize: Global.ds(16), color: ColorUtil.color("#FAFAFA")), textAlign: TextAlign.right),
          ),
          Expanded(
            child: Container(
              height: Global.ds(40),
              alignment: Alignment.centerLeft,
              padding: EdgeInsets.symmetric(horizontal: Global.ds(15)),
              decoration: BoxDecoration(
                color: ColorUtil.color("#366485"),
                border: Border.all(color: ColorUtil.color("#3B99CC")),
                borderRadius: BorderRadius.circular(Global.ds(20)),
              ),
              child: Dropdown<RadioState>(
                key: UniqueKey(),
                options: RadioState.values.where((e) => e != RadioState.idle).map((e) => DropdownMenuItem<RadioState>(value: e, child: Text(e.name))).toList(),
                initialValue: radioState,
                hintText: "请选择传输模式",
                fontSize: Global.ds(18),
                fontColor: ColorUtil.color("#ABDBF3"),
                dropdownColor: ColorUtil.color("#1A263D"),
                onChanged: (value) => setState(() => radioState = value),
              ),
            ),
          ),
        ],
      ),
    ];
    if (radioState == RadioState.send) {
      list.addAll([
        Row(
          children: [
            Container(
              width: Global.ds(86),
              height: Global.ds(40),
              alignment: Alignment.centerRight,
              child: Text("发射频率：", style: TextStyle(fontSize: Global.ds(16), color: ColorUtil.color("#FAFAFA")), textAlign: TextAlign.right),
            ),
            Expanded(
              child: Container(
                height: Global.ds(40),
                alignment: Alignment.centerLeft,
                padding: EdgeInsets.symmetric(horizontal: Global.ds(15)),
                decoration: BoxDecoration(
                  color: ColorUtil.color("#366485"),
                  border: Border.all(color: ColorUtil.color("#3B99CC")),
                  borderRadius: BorderRadius.circular(Global.ds(20)),
                ),
                child: InputField(
                  key: UniqueKey(),
                  initialValue: "${sendMHz ?? ''}",
                  hintText: "输入频率",
                  keyboardType: const TextInputType.numberWithOptions(decimal: true),
                  textStyle: TextStyle(fontSize: Global.ds(18), height: 1, color: ColorUtil.color("#ABDBF3")),
                  hintStyle: TextStyle(color: ColorUtil.color("#ABDBF3").withOpacity(.5)),
                  onChanged: (controller, focusNode, value) => sendMHz = double.tryParse(value),
                ),
              ),
            ),
            VerticalDivider(width: Global.ds(5), color: Colors.transparent),
            Text("MHz", style: TextStyle(fontSize: Global.ds(16), color: ColorUtil.color("#FAFAFA"))),
            VerticalDivider(width: Global.ds(40), color: Colors.transparent),
            Container(
              width: Global.ds(86),
              height: Global.ds(40),
              alignment: Alignment.centerRight,
              child: Text("发射功率：", style: TextStyle(fontSize: Global.ds(16), color: ColorUtil.color("#FAFAFA")), textAlign: TextAlign.right),
            ),
            Expanded(
              child: Container(
                height: Global.ds(40),
                alignment: Alignment.centerLeft,
                padding: EdgeInsets.symmetric(horizontal: Global.ds(15)),
                decoration: BoxDecoration(
                  color: ColorUtil.color("#366485"),
                  border: Border.all(color: ColorUtil.color("#3B99CC")),
                  borderRadius: BorderRadius.circular(Global.ds(20)),
                ),
                child: Dropdown<PowerType>(
                  key: UniqueKey(),
                  options: PowerType.values.map((e) => DropdownMenuItem<PowerType>(value: e, child: Text(e.name))).toList(),
                  initialValue: powerType,
                  hintText: "请选择",
                  fontSize: Global.ds(18),
                  fontColor: ColorUtil.color("#ABDBF3"),
                  dropdownColor: ColorUtil.color("#1A263D"),
                  onChanged: (value) => powerType = value,
                ),
              ),
            ),
          ],
        ),
        Row(
          children: [
            Container(
              width: Global.ds(86),
              height: Global.ds(40),
              alignment: Alignment.centerRight,
              child: Text("数据：", style: TextStyle(fontSize: Global.ds(16), color: ColorUtil.color("#FAFAFA")), textAlign: TextAlign.right),
            ),
            Expanded(
              child: Container(
                height: Global.ds(40),
                alignment: Alignment.centerLeft,
                padding: EdgeInsets.symmetric(horizontal: Global.ds(15)),
                decoration: BoxDecoration(
                  color: ColorUtil.color("#366485"),
                  border: Border.all(color: ColorUtil.color("#3B99CC")),
                  borderRadius: BorderRadius.circular(Global.ds(20)),
                ),
                child: InputField(
                  key: UniqueKey(),
                  initialValue: data2 ?? '',
                  hintText: "输入数据",
                  maxLength: 32,
                  textStyle: TextStyle(fontSize: Global.ds(18), height: 1, color: ColorUtil.color("#ABDBF3")),
                  hintStyle: TextStyle(color: ColorUtil.color("#ABDBF3").withOpacity(.5)),
                  onChanged: (controller, focusNode, value) => data2 = value.trim(),
                ),
              ),
            ),
            VerticalDivider(width: Global.ds(20), color: Colors.transparent),
            TextButton(
              onPressed: () {
                if (sendMHz == null) {
                  ToastUtil.failure("请输入发射频率");
                } else if (sendMHz! <= 0) {
                  ToastUtil.failure("发射频率无效");
                } else if (powerType == null) {
                  ToastUtil.failure("请选择发射功率");
                } else if (data2?.isEmpty ?? true) {
                  ToastUtil.failure("请输入数据");
                } else {
                  ApiUtil().sendLoraData({"lora_msg": data2, "freq": (sendMHz! * 1000000).round(), "power": powerType!.index}).then((res) {
                    msg.insert(0, "发射数据: $data2, 频率: ${sendMHz}MHz, 功率: ${powerType!.name}");
                    _msgKey.currentState?.setState(() {});
                  }).catchError((error) {
                    ToastUtil.error(error.toString());
                  });
                }
              },
              style: TextButton.styleFrom(
                fixedSize: Size(Global.ds(100), Global.ds(40)),
                textStyle: TextStyle(fontSize: Global.ds(18)),
                foregroundColor: Colors.white,
                backgroundColor: ColorUtil.color("#2CA6E0"),
                shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(Global.ds(20))),
              ),
              child: const Text("GO"),
            ),
          ],
        ),
      ]);
    } else if (radioState == RadioState.receive) {
      list.add(Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Container(
            width: Global.ds(86),
            height: Global.ds(40),
            alignment: Alignment.centerRight,
            child: Text("接收频率：", style: TextStyle(fontSize: Global.ds(16), color: ColorUtil.color("#FAFAFA")), textAlign: TextAlign.right),
          ),
          Expanded(
            child: Container(
              height: Global.ds(40),
              alignment: Alignment.centerLeft,
              padding: EdgeInsets.symmetric(horizontal: Global.ds(15)),
              decoration: BoxDecoration(
                color: ColorUtil.color("#366485"),
                border: Border.all(color: ColorUtil.color("#3B99CC")),
                borderRadius: BorderRadius.circular(Global.ds(20)),
              ),
              child: InputField(
                key: UniqueKey(),
                initialValue: "${receiveMHz ?? ''}",
                hintText: "输入频率",
                keyboardType: const TextInputType.numberWithOptions(decimal: true),
                textStyle: TextStyle(fontSize: Global.ds(18), height: 1, color: ColorUtil.color("#ABDBF3")),
                hintStyle: TextStyle(color: ColorUtil.color("#ABDBF3").withOpacity(.5)),
                onChanged: (controller, focusNode, value) => receiveMHz = double.tryParse(value),
              ),
            ),
          ),
          VerticalDivider(width: Global.ds(5), color: Colors.transparent),
          Text("MHz", style: TextStyle(fontSize: Global.ds(16), color: ColorUtil.color("#FAFAFA"))),
          VerticalDivider(width: Global.ds(40), color: Colors.transparent),
          TextButton(
            onPressed: () {
              if (receiveMHz == null) {
                ToastUtil.failure("请输入接收频率");
              } else if (receiveMHz! <= 0) {
                ToastUtil.failure("接收频率无效");
              } else {
                int freq = (receiveMHz! * 1000000).round();
                ApiUtil().setLoraReceiveFreq(freq).then((res) {
                  msg.insert(0, "设置接收频率: ${receiveMHz}MHz");
                  _msgKey.currentState?.setState(() {});
                }).catchError((error) {
                  ToastUtil.error(error.toString());
                });
              }
            },
            style: TextButton.styleFrom(
              fixedSize: Size(Global.ds(100), Global.ds(40)),
              textStyle: TextStyle(fontSize: Global.ds(18)),
              foregroundColor: Colors.white,
              backgroundColor: ColorUtil.color("#2CA6E0"),
              shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(Global.ds(20))),
            ),
            child: const Text("GO"),
          ),
        ],
      ));
    }
    return list;
  }
}

class DisabledMHz extends StatefulWidget {
  const DisabledMHz({super.key});

  @override
  State<DisabledMHz> createState() => _DisabledMHzState();
}

class _DisabledMHzState extends State<DisabledMHz> {
  int? unfoldId;

  @override
  Widget build(BuildContext context) => Column(
        crossAxisAlignment: CrossAxisAlignment.stretch,
        children: [
          Flexible(
            child: FutureWidget<List<DisabledMHzEntity>>(
              future: DBApi.disabledMHz.list(),
              loadingDesc: "正在读取禁用频率版本列表",
              doneBuilder: (context, snapshot) => StatefulBuilder(
                builder: (context, stateSetter) => ListView.separated(
                  reverse: true,
                  shrinkWrap: true,
                  padding: EdgeInsets.zero,
                  itemCount: snapshot.requireData.length,
                  itemBuilder: (context, index) => _renderItem(snapshot.requireData[snapshot.requireData.length - index - 1], stateSetter),
                  separatorBuilder: (BuildContext context, int index) => Divider(
                    height: 1,
                    thickness: 1,
                    color: ColorUtil.color("#1A263D"),
                    indent: Global.ds(20),
                    endIndent: Global.ds(20),
                  ),
                ),
              ),
            ),
          ),
          Padding(
            padding: EdgeInsets.all(Global.ds(20)),
            child: IconButton(
              onPressed: () async {
                unfoldId = (await DBApi.disabledMHz.insert(DisabledMHzEntity("")))?.id;
                setState(() {});
              },
              icon: ImageUtil.icon("static/images/icon/plus.png"),
              style: IconButton.styleFrom(
                iconSize: Global.ds(24),
                fixedSize: Size.fromHeight(Global.ds(40)),
                foregroundColor: ColorUtil.color("#036EB7"),
                backgroundColor: ColorUtil.color("#46E5CB"),
                shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(Global.ds(20))),
              ),
            ),
          ),
        ],
      );

  Widget _renderItem(DisabledMHzEntity entity, StateSetter listStateSetter) {
    bool added = false;
    List<double> mhz = entity.mhz;
    return Column(crossAxisAlignment: CrossAxisAlignment.stretch, children: [
      InkWell(
        onTap: () => listStateSetter(() => unfoldId = unfoldId == entity.id ? null : entity.id),
        child: Ink(
          height: Global.ds(60),
          color: ColorUtil.color("#1A3959"),
          padding: EdgeInsets.symmetric(horizontal: Global.ds(20)),
          child: Center(
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                ImageUtil.icon("static/images/icon/9.png", size: Global.ds(20), color: ColorUtil.color("#74C8CE")),
                VerticalDivider(width: Global.ds(10), color: Colors.transparent),
                Text("V${entity.id}", style: TextStyle(fontSize: Global.ds(18), fontWeight: FontWeight.w700, color: ColorUtil.color("#74C8CE"))),
                const Spacer(),
                IconButton(
                  onPressed: () => ModalUtil.confirm(content: "删除后不可以恢复，并且关联该版本的禁用频率也将失效，确定要删除吗？").then((value) {
                    if (value == true) {
                      DBApi.disabledMHz.delete(entity.id!).then((value) {
                        setState(() {});
                        ToastUtil.success("版本删除成功");
                      });
                    }
                  }),
                  icon: ImageUtil.icon("static/images/icon/6.png"),
                  style: IconButton.styleFrom(iconSize: Global.ds(24), fixedSize: Size.fromHeight(Global.ds(60)), foregroundColor: ColorUtil.color("#D95348")),
                ),
                VerticalDivider(width: Global.ds(20), color: Colors.transparent),
                AnimatedRotation(
                  key: ValueKey<String>("AnimatedRotation-DisabledMHz-${entity.id}"),
                  turns: unfoldId == entity.id ? 0.25 : 0,
                  curve: Curves.fastOutSlowIn,
                  filterQuality: FilterQuality.high,
                  duration: const Duration(milliseconds: 300),
                  child: Icon(Icons.arrow_forward_ios, size: Global.ds(18), color: ColorUtil.color("#2CA6E0")),
                ),
              ],
            ),
          ),
        ),
      ),
      AnimatedSwitcher(
        key: ValueKey<String>("AnimatedSwitcher-DisabledMHz-${entity.id}"),
        switchInCurve: Curves.fastOutSlowIn,
        switchOutCurve: Curves.fastOutSlowIn,
        duration: const Duration(milliseconds: 300),
        transitionBuilder: (child, animation) => SizeTransition(sizeFactor: animation, child: child),
        child: unfoldId == entity.id
            ? Container(
                alignment: AlignmentDirectional.centerStart,
                color: ColorUtil.color("#1A263D"),
                padding: EdgeInsets.only(left: Global.ds(50), top: Global.ds(20), right: Global.ds(20), bottom: Global.ds(20)),
                child: StatefulBuilder(
                  builder: (context, itemStateSetter) {
                    List<Widget> widgets = mhz
                        .asMap()
                        .keys
                        .map<Widget>((i) => Container(
                              height: Global.ds(40),
                              decoration: BoxDecoration(
                                color: ColorUtil.color("#2B526F"),
                                borderRadius: BorderRadius.circular(Global.ds(20)),
                              ),
                              child: Row(
                                mainAxisSize: MainAxisSize.min,
                                mainAxisAlignment: MainAxisAlignment.center,
                                children: [
                                  VerticalDivider(width: Global.ds(15), color: Colors.transparent),
                                  Text("${mhz[i]}MHz", style: TextStyle(fontSize: Global.ds(18), color: Colors.white)),
                                  IconButton(
                                    onPressed: () {
                                      mhz.removeAt(i);
                                      entity.values = mhz.join(',');
                                      DBApi.disabledMHz.update(entity).then((value) {
                                        itemStateSetter(() {});
                                        ToastUtil.success("删除成功");
                                      });
                                    },
                                    icon: ImageUtil.icon("static/images/icon/close.png"),
                                    style: IconButton.styleFrom(iconSize: Global.ds(20), foregroundColor: ColorUtil.color("#FBD580")),
                                  ),
                                ],
                              ),
                            ))
                        .toList();
                    widgets.add(StatefulBuilder(builder: (context, addStateSetter) {
                      if (added) {
                        return Container(
                          width: Global.ds(160),
                          height: Global.ds(40),
                          alignment: Alignment.centerLeft,
                          padding: EdgeInsets.symmetric(horizontal: Global.ds(15)),
                          decoration: BoxDecoration(
                            color: ColorUtil.color("#366485"),
                            borderRadius: BorderRadius.circular(Global.ds(20)),
                          ),
                          child: InputField(
                            key: UniqueKey(),
                            hintText: "输入频率",
                            autofocus: true,
                            keyboardType: const TextInputType.numberWithOptions(decimal: true),
                            textStyle: TextStyle(fontSize: Global.ds(18), height: 1, color: Colors.white),
                            hintStyle: TextStyle(color: Colors.white.withOpacity(.5)),
                            suffix: const Text("MHz"),
                            onBlur: (controller, focusNode, value) => addStateSetter(() => added = false),
                            onSubmitted: (controller, focusNode, value) {
                              double? val = double.tryParse(value);
                              if (val != null) {
                                if (mhz.contains(val)) {
                                  ToastUtil.error("输入的值已存在");
                                } else {
                                  mhz.add(val);
                                  entity.values = mhz.join(',');
                                  DBApi.disabledMHz.update(entity).then((value) {
                                    itemStateSetter(() => added = false);
                                    ToastUtil.success("添加成功");
                                  });
                                }
                              } else {
                                ToastUtil.error("输入的值有误");
                              }
                            },
                          ),
                        );
                      } else {
                        return IconButton(
                          onPressed: () => addStateSetter(() => added = true),
                          icon: ImageUtil.icon("static/images/icon/plus.png"),
                          style: IconButton.styleFrom(
                            iconSize: Global.ds(24),
                            fixedSize: Size(Global.ds(120), Global.ds(40)),
                            foregroundColor: ColorUtil.color("#036EB7"),
                            backgroundColor: ColorUtil.color("#46E5CB"),
                            shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(Global.ds(20))),
                          ),
                        );
                      }
                    }));
                    return Wrap(spacing: Global.ds(20), runSpacing: Global.ds(20), children: widgets);
                  },
                ),
              )
            : null,
      ),
    ]);
  }
}

class Transmission extends StatefulWidget {
  const Transmission({super.key});

  @override
  State<Transmission> createState() => _TransmissionState();
}

class _TransmissionState extends State<Transmission> with AutomaticKeepAliveClientMixin {
  final List<String> type = ['低速传输', '文本短信', '语音短信', '数字语音', '模拟语音'];
  final TextEditingController _input0Controller = TextEditingController(), _input1Controller = TextEditingController();
  int? current = 0, radioId, bestId;
  double? mhz;
  PowerType? sendPower, positivePower, negativePower;

  @override
  void dispose() {
    _input0Controller.dispose();
    _input1Controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      crossAxisAlignment: CrossAxisAlignment.stretch,
      children: [
        Expanded(
          child: ClipRRect(
            borderRadius: BorderRadius.circular(Global.ds(16)),
            child: Builder(
              builder: (context) => ResizeStateBuilder(
                parent: context,
                resizeToAvoidBottomInset: true,
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.stretch,
                  children: [
                    Expanded(
                      child: Container(
                        color: ColorUtil.color("#192847"),
                        child: current == 4
                            ? Center(child: ImageUtil.asset("static/images/ptt/simulate.png", width: Global.ds(90), height: Global.ds(92)))
                            : current == 3
                                ? Center(child: ImageUtil.asset("static/images/ptt/digit.png", width: Global.ds(138), height: Global.ds(108)))
                                : _chatList,
                      ),
                    ),
                    _sendPanel,
                  ],
                ),
              ),
            ),
          ),
        ),
        VerticalDivider(width: Global.ds(10), color: Colors.transparent),
        Expanded(
          child: Container(
            decoration: BoxDecoration(borderRadius: BorderRadius.circular(Global.ds(16)), color: ColorUtil.color("#153252")),
            padding: EdgeInsets.symmetric(vertical: Global.ds(30)),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.stretch,
              children: [
                Padding(
                  padding: EdgeInsets.symmetric(horizontal: Global.ds(30)),
                  child: Row(
                    children: [
                      Container(
                        width: Global.ds(86),
                        height: Global.ds(40),
                        alignment: Alignment.centerRight,
                        child: Text("传输台站：", style: TextStyle(fontSize: Global.ds(16), color: ColorUtil.color("#FAFAFA")), textAlign: TextAlign.right),
                      ),
                      Expanded(
                        child: Container(
                          height: Global.ds(40),
                          alignment: Alignment.centerLeft,
                          padding: EdgeInsets.symmetric(horizontal: Global.ds(15)),
                          decoration: BoxDecoration(
                            color: ColorUtil.color("#366485"),
                            border: Border.all(color: ColorUtil.color("#3B99CC")),
                            borderRadius: BorderRadius.circular(Global.ds(20)),
                          ),
                          child: FutureWidget<List<RadioEntity>>(
                            future: DBApi.radio.list("`id` != ?", [context.read<StateNotifier>().localId]),
                            doneBuilder: (context, snapshot) => Dropdown<int>(
                              key: UniqueKey(),
                              initialValue: radioId,
                              options: snapshot.requireData.map((e) => DropdownMenuItem<int>(value: e.id, child: Text(e.name))).toList(),
                              hintText: "请选择传输台站",
                              fontSize: Global.ds(18),
                              fontColor: ColorUtil.color("#ABDBF3"),
                              dropdownColor: ColorUtil.color("#1A263D"),
                              onChanged: (value) => setState(() => radioId = value),
                            ),
                          ),
                        ),
                      ),
                    ],
                  ),
                ),
                Divider(height: Global.ds(20), color: Colors.transparent),
                Padding(
                  padding: EdgeInsets.symmetric(horizontal: Global.ds(30)),
                  child: Row(
                    children: [
                      Container(
                        width: Global.ds(86),
                        height: Global.ds(40),
                        alignment: Alignment.centerRight,
                        child: Text("选频方案：", style: TextStyle(fontSize: Global.ds(16), color: ColorUtil.color("#FAFAFA")), textAlign: TextAlign.right),
                      ),
                      Expanded(
                        child: Container(
                          height: Global.ds(40),
                          alignment: Alignment.centerLeft,
                          padding: EdgeInsets.symmetric(horizontal: Global.ds(15)),
                          decoration: BoxDecoration(
                            color: ColorUtil.color("#366485"),
                            border: Border.all(color: ColorUtil.color("#3B99CC")),
                            borderRadius: BorderRadius.circular(Global.ds(20)),
                          ),
                          child: radioId == null
                              ? Text("请先选择传输台站", style: TextStyle(fontSize: Global.ds(18), color: ColorUtil.color("#ABDBF3")))
                              : FutureWidget<List<DetectTaskBestEntity>>(
                                  future: DBApi.detectTaskBest.list(TaskType.pick, radioId),
                                  doneBuilder: (context, snapshot) {
                                    List<DetectTaskBestEntity> result = snapshot.requireData;
                                    if (result.isEmpty) {
                                      bestId = null;
                                      return Text("该台站暂无选频方案", style: TextStyle(fontSize: Global.ds(18), color: ColorUtil.color("#ABDBF3")));
                                    } else {
                                      bestId = snapshot.requireData.map((e) => e.id!).contains(bestId) ? bestId : null;
                                      return Dropdown<int>(
                                        key: UniqueKey(),
                                        initialValue: bestId,
                                        options: snapshot.requireData.map((e) => DropdownMenuItem<int>(value: e.id, child: Text(e.name))).toList(),
                                        hintText: "请选择选频方案",
                                        fontSize: Global.ds(18),
                                        fontColor: ColorUtil.color("#ABDBF3"),
                                        dropdownColor: ColorUtil.color("#1A263D"),
                                        onChanged: (value) {
                                          bestId = value;
                                          DBApi.detectTaskBest.pickResult(bestId!, true).then((value) {
                                            setState(() => mhz = Global.toFixed(value.single.hz, 3));
                                          });
                                        },
                                      );
                                    }
                                  },
                                ),
                        ),
                      ),
                    ],
                  ),
                ),
                Divider(height: Global.ds(20), color: Colors.transparent),
                Padding(
                  padding: EdgeInsets.symmetric(horizontal: Global.ds(30)),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      Container(
                        width: Global.ds(86),
                        height: Global.ds(40),
                        alignment: Alignment.centerRight,
                        child: Text("传输频率：", style: TextStyle(fontSize: Global.ds(16), color: ColorUtil.color("#FAFAFA")), textAlign: TextAlign.right),
                      ),
                      Expanded(
                        child: Container(
                          height: Global.ds(40),
                          alignment: Alignment.centerLeft,
                          padding: EdgeInsets.symmetric(horizontal: Global.ds(15)),
                          decoration: BoxDecoration(
                            color: ColorUtil.color("#366485"),
                            border: Border.all(color: ColorUtil.color("#3B99CC")),
                            borderRadius: BorderRadius.circular(Global.ds(20)),
                          ),
                          child: InputField(
                            key: UniqueKey(),
                            hintText: "输入频率",
                            initialValue: "${mhz ?? ''}",
                            keyboardType: const TextInputType.numberWithOptions(decimal: true),
                            textStyle: TextStyle(fontSize: Global.ds(18), height: 1, color: ColorUtil.color("#ABDBF3")),
                            hintStyle: TextStyle(color: ColorUtil.color("#ABDBF3").withOpacity(.5)),
                            onSubmitted: (controller, focusNode, value) => setState(() => mhz = double.tryParse(value)),
                          ),
                        ),
                      ),
                      VerticalDivider(width: Global.ds(5), color: Colors.transparent),
                      Text("MHz", style: TextStyle(fontSize: Global.ds(16), color: ColorUtil.color("#FAFAFA"))),
                      VerticalDivider(width: Global.ds(40), color: Colors.transparent),
                      Container(
                        width: Global.ds(86),
                        height: Global.ds(40),
                        alignment: Alignment.centerRight,
                        child: Text("发送功率：", style: TextStyle(fontSize: Global.ds(16), color: ColorUtil.color("#FAFAFA")), textAlign: TextAlign.right),
                      ),
                      Expanded(
                        child: Container(
                          height: Global.ds(40),
                          alignment: Alignment.centerLeft,
                          padding: EdgeInsets.symmetric(horizontal: Global.ds(15)),
                          decoration: BoxDecoration(
                            color: ColorUtil.color("#366485"),
                            border: Border.all(color: ColorUtil.color("#3B99CC")),
                            borderRadius: BorderRadius.circular(Global.ds(20)),
                          ),
                          child: Dropdown<PowerType>(
                            key: UniqueKey(),
                            options: PowerType.values.map((e) => DropdownMenuItem<PowerType>(value: e, child: Text(e.name))).toList(),
                            initialValue: sendPower,
                            hintText: "请选择",
                            fontSize: Global.ds(18),
                            fontColor: ColorUtil.color("#ABDBF3"),
                            dropdownColor: ColorUtil.color("#1A263D"),
                            onChanged: (value) => setState(() => sendPower = value),
                          ),
                        ),
                      ),
                    ],
                  ),
                ),
                Divider(height: Global.ds(40), thickness: 1, color: ColorUtil.color("#1A263D")),
                Padding(
                  padding: EdgeInsets.symmetric(horizontal: Global.ds(30)),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      Container(
                        width: Global.ds(86),
                        height: Global.ds(40),
                        alignment: Alignment.centerRight,
                        child: Text("正向功率：", style: TextStyle(fontSize: Global.ds(16), color: ColorUtil.color("#FAFAFA")), textAlign: TextAlign.right),
                      ),
                      Expanded(
                        child: Container(
                          height: Global.ds(40),
                          alignment: Alignment.centerLeft,
                          padding: EdgeInsets.symmetric(horizontal: Global.ds(15)),
                          decoration: BoxDecoration(
                            color: ColorUtil.color("#366485"),
                            border: Border.all(color: ColorUtil.color("#3B99CC")),
                            borderRadius: BorderRadius.circular(Global.ds(20)),
                          ),
                          child: Dropdown<PowerType>(
                            key: UniqueKey(),
                            options: PowerType.values.map((e) => DropdownMenuItem<PowerType>(value: e, child: Text(e.name))).toList(),
                            initialValue: positivePower,
                            hintText: "请选择",
                            fontSize: Global.ds(18),
                            fontColor: ColorUtil.color("#ABDBF3"),
                            dropdownColor: ColorUtil.color("#1A263D"),
                            onChanged: (value) => setState(() => positivePower = value),
                          ),
                        ),
                      ),
                      VerticalDivider(width: Global.ds(40), color: Colors.transparent),
                      Container(
                        width: Global.ds(86),
                        height: Global.ds(40),
                        alignment: Alignment.centerRight,
                        child: Text("反向功率：", style: TextStyle(fontSize: Global.ds(16), color: ColorUtil.color("#FAFAFA")), textAlign: TextAlign.right),
                      ),
                      Expanded(
                        child: Container(
                          height: Global.ds(40),
                          alignment: Alignment.centerLeft,
                          padding: EdgeInsets.symmetric(horizontal: Global.ds(15)),
                          decoration: BoxDecoration(
                            color: ColorUtil.color("#366485"),
                            border: Border.all(color: ColorUtil.color("#3B99CC")),
                            borderRadius: BorderRadius.circular(Global.ds(20)),
                          ),
                          child: Dropdown<PowerType>(
                            key: UniqueKey(),
                            options: PowerType.values.map((e) => DropdownMenuItem<PowerType>(value: e, child: Text(e.name))).toList(),
                            initialValue: negativePower,
                            hintText: "请选择",
                            fontSize: Global.ds(18),
                            fontColor: ColorUtil.color("#ABDBF3"),
                            dropdownColor: ColorUtil.color("#1A263D"),
                            onChanged: (value) => setState(() => negativePower = value),
                          ),
                        ),
                      ),
                    ],
                  ),
                ),
                Divider(height: Global.ds(40), thickness: 1, color: ColorUtil.color("#1A263D")),
                Padding(
                  padding: EdgeInsets.symmetric(horizontal: Global.ds(30)),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      Container(
                        width: Global.ds(86),
                        height: Global.ds(40),
                        alignment: Alignment.centerRight,
                        child: Text("传输方式：", style: TextStyle(fontSize: Global.ds(16), color: ColorUtil.color("#FAFAFA")), textAlign: TextAlign.right),
                      ),
                      Expanded(
                        child: Container(
                          height: Global.ds(40),
                          alignment: Alignment.centerLeft,
                          padding: EdgeInsets.symmetric(horizontal: Global.ds(15)),
                          decoration: BoxDecoration(
                            color: ColorUtil.color("#366485"),
                            border: Border.all(color: ColorUtil.color("#3B99CC")),
                            borderRadius: BorderRadius.circular(Global.ds(20)),
                          ),
                          child: Dropdown<int>(
                            key: UniqueKey(),
                            options: type.asMap().keys.map((i) => DropdownMenuItem<int>(value: i, child: Text(type[i]))).toList(),
                            initialValue: current,
                            hintText: "请选择",
                            fontSize: Global.ds(18),
                            fontColor: ColorUtil.color("#ABDBF3"),
                            dropdownColor: ColorUtil.color("#1A263D"),
                            onChanged: (value) => setState(() => current = value),
                          ),
                        ),
                      ),
                    ],
                  ),
                ),
              ],
            ),
          ),
        ),
      ],
    );
  }

  Widget get _chatList => radioId == null
      ? const Center()
      : Consumer<ChatNotifier>(
          builder: (context, notifier, child) => FutureWidget<List<ChatEntity>>(
            future: DBApi.chat.list(context.read<StateNotifier>().localId, radioId!),
            doneBuilder: (context, snapshot) {
              List<ChatEntity> result = snapshot.requireData;
              return ListView.separated(
                reverse: true,
                shrinkWrap: true,
                itemCount: result.length,
                padding: EdgeInsets.symmetric(horizontal: Global.ds(30)),
                itemBuilder: (context, index) {
                  ChatEntity entity = result[index];
                  bool isLocal = entity.isLocal(context.read<StateNotifier>().localId);
                  return Row(
                    mainAxisSize: MainAxisSize.min,
                    crossAxisAlignment: CrossAxisAlignment.start,
                    mainAxisAlignment: isLocal ? MainAxisAlignment.end : MainAxisAlignment.start,
                    children: isLocal
                        ? [
                            ConstrainedBox(
                              constraints: BoxConstraints(maxWidth: (Global.windowSize.width - Global.ds(40)) / 2 - Global.ds(140)),
                              child: IntrinsicWidth(
                                child: Column(
                                  mainAxisSize: MainAxisSize.min,
                                  crossAxisAlignment: CrossAxisAlignment.stretch,
                                  children: [
                                    Container(
                                      height: Global.ds(20),
                                      alignment: Alignment.centerRight,
                                      child: DefaultTextStyle(
                                        style: TextStyle(fontSize: Global.ds(14), height: 1, color: Colors.grey),
                                        child: Row(
                                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                          children: [Text(entity.time), VerticalDivider(width: Global.ds(10), color: Colors.transparent), Text(entity.senderName!)],
                                        ),
                                      ),
                                    ),
                                    Material(
                                      color: ColorUtil.color("#A8EA7C"),
                                      clipBehavior: Clip.antiAlias,
                                      borderRadius: BorderRadius.circular(Global.ds(4)),
                                      child: InkWell(
                                        onTap: () {},
                                        child: Padding(
                                          padding: EdgeInsets.symmetric(horizontal: Global.ds(15), vertical: Global.ds(5)),
                                          child: Align(alignment: Alignment.centerRight, child: Text(entity.content, style: TextStyle(fontSize: Global.ds(18), color: Colors.black))),
                                        ),
                                      ),
                                    ),
                                  ],
                                ),
                              ),
                            ),
                            Container(
                              margin: EdgeInsets.only(left: Global.ds(10), top: Global.ds(20)),
                              child: ImageUtil.icon("static/images/icon/avatar.png", size: Global.ds(30), color: ColorUtil.color("#A8EA7C")),
                            ),
                          ]
                        : [
                            Container(
                              margin: EdgeInsets.only(right: Global.ds(10), top: Global.ds(20)),
                              child: ImageUtil.icon("static/images/icon/avatar.png", size: Global.ds(30), color: Colors.white),
                            ),
                            ConstrainedBox(
                              constraints: BoxConstraints(maxWidth: (Global.windowSize.width - Global.ds(40)) / 2 - Global.ds(140)),
                              child: IntrinsicWidth(
                                child: Column(
                                  mainAxisSize: MainAxisSize.min,
                                  crossAxisAlignment: CrossAxisAlignment.stretch,
                                  children: [
                                    Container(
                                      height: Global.ds(20),
                                      alignment: Alignment.centerLeft,
                                      child: DefaultTextStyle(
                                        style: TextStyle(fontSize: Global.ds(14), height: 1, color: Colors.grey),
                                        child: Row(
                                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                          children: [Text(entity.senderName!), VerticalDivider(width: Global.ds(10), color: Colors.transparent), Text(entity.time)],
                                        ),
                                      ),
                                    ),
                                    Material(
                                      color: Colors.white,
                                      clipBehavior: Clip.antiAlias,
                                      borderRadius: BorderRadius.circular(Global.ds(4)),
                                      child: InkWell(
                                        onTap: () {},
                                        child: Padding(
                                          padding: EdgeInsets.symmetric(horizontal: Global.ds(15), vertical: Global.ds(5)),
                                          child: Align(
                                            alignment: Alignment.centerLeft,
                                            child: Text(entity.content, style: TextStyle(fontSize: Global.ds(18), color: Colors.black)),
                                          ),
                                        ),
                                      ),
                                    ),
                                  ],
                                ),
                              ),
                            ),
                          ],
                  );
                },
                separatorBuilder: (context, index) => Divider(height: Global.ds(20), color: Colors.transparent),
              );
            },
          ),
        );

  Widget get _sendPanel => [
        StatefulBuilder(
          builder: (context, stateSetter) => Column(
            crossAxisAlignment: CrossAxisAlignment.stretch,
            children: [
              Container(
                alignment: Alignment.centerLeft,
                color: ColorUtil.color("#192847"),
                padding: EdgeInsets.symmetric(horizontal: Global.ds(15), vertical: Global.ds(10)),
                child: Text("低速传输（限字${_input0Controller.value.text.length}/5）", style: TextStyle(fontSize: Global.ds(14), color: ColorUtil.color("#2CA6E0"))),
              ),
              Container(
                color: ColorUtil.color("#144D93"),
                padding: EdgeInsets.symmetric(horizontal: Global.ds(15), vertical: Global.ds(10)),
                child: Container(
                  height: Global.ds(40),
                  clipBehavior: Clip.antiAlias,
                  decoration: BoxDecoration(borderRadius: BorderRadius.circular(Global.ds(8))),
                  child: Row(
                    crossAxisAlignment: CrossAxisAlignment.stretch,
                    children: [
                      Expanded(
                        child: Container(
                          color: Colors.white,
                          alignment: Alignment.centerLeft,
                          padding: EdgeInsets.symmetric(horizontal: Global.ds(15)),
                          child: InputField(
                            key: const ValueKey<String>("Transmission-Input0"),
                            controller: _input0Controller,
                            hintText: "低速传输限5字",
                            maxLength: 5,
                            disabled: radioId == null,
                            textStyle: TextStyle(fontSize: Global.ds(18), height: 1, color: Colors.black),
                            hintStyle: TextStyle(color: Colors.black.withOpacity(.5)),
                            onChanged: (controller, focusNode, value) => stateSetter(() {}),
                            onSubmitted: (controller, focusNode, value) {},
                          ),
                        ),
                      ),
                      GestureDetector(
                        onTap: _input0Controller.value.text.isEmpty || radioId == null ? null : () {},
                        child: Container(
                          width: Global.ds(130),
                          decoration: _input0Controller.value.text.isEmpty
                              ? const BoxDecoration(color: Colors.grey)
                              : BoxDecoration(
                                  gradient: LinearGradient(
                                    begin: Alignment.bottomCenter,
                                    end: Alignment.topCenter,
                                    colors: [
                                      ColorUtil.color("#1E6458"),
                                      ColorUtil.color("#178677"),
                                      ColorUtil.color("#25C2BD"),
                                      ColorUtil.color("#46E5CB"),
                                      ColorUtil.color("#14706D"),
                                    ],
                                    stops: const [0, 0, .53, 1, 1],
                                  ),
                                ),
                          child: Center(child: Text("发送", style: TextStyle(fontSize: Global.ds(16), color: ColorUtil.color("#FAFAFA")))),
                        ),
                      ),
                    ],
                  ),
                ),
              )
            ],
          ),
        ),
        StatefulBuilder(
          builder: (context, stateSetter) => Column(
            crossAxisAlignment: CrossAxisAlignment.stretch,
            children: [
              Container(
                alignment: Alignment.centerLeft,
                color: ColorUtil.color("#192847"),
                padding: EdgeInsets.symmetric(horizontal: Global.ds(15), vertical: Global.ds(10)),
                child: Text("文本短信（限字${_input1Controller.value.text.length}/15）", style: TextStyle(fontSize: Global.ds(14), color: ColorUtil.color("#2CA6E0"))),
              ),
              Container(
                color: ColorUtil.color("#144D93"),
                padding: EdgeInsets.symmetric(horizontal: Global.ds(15), vertical: Global.ds(10)),
                child: Container(
                  height: Global.ds(40),
                  clipBehavior: Clip.antiAlias,
                  decoration: BoxDecoration(borderRadius: BorderRadius.circular(Global.ds(8))),
                  child: Row(
                    crossAxisAlignment: CrossAxisAlignment.stretch,
                    children: [
                      Expanded(
                        child: Container(
                          color: Colors.white,
                          alignment: Alignment.centerLeft,
                          padding: EdgeInsets.symmetric(horizontal: Global.ds(15)),
                          child: InputField(
                            key: const ValueKey<String>("Transmission-Input1"),
                            controller: _input1Controller,
                            hintText: "文本短信限15字",
                            maxLength: 15,
                            disabled: radioId == null,
                            textStyle: TextStyle(fontSize: Global.ds(18), height: 1, color: Colors.black),
                            hintStyle: TextStyle(color: Colors.black.withOpacity(.5)),
                            onChanged: (controller, focusNode, value) => stateSetter(() {}),
                            onSubmitted: (controller, focusNode, value) => sendText(stateSetter),
                          ),
                        ),
                      ),
                      GestureDetector(
                        onTap: _input1Controller.value.text.isEmpty || radioId == null ? null : () => sendText(stateSetter),
                        child: Container(
                          width: Global.ds(130),
                          decoration: _input1Controller.value.text.isEmpty
                              ? const BoxDecoration(color: Colors.grey)
                              : BoxDecoration(
                                  gradient: LinearGradient(
                                    begin: Alignment.bottomCenter,
                                    end: Alignment.topCenter,
                                    colors: [
                                      ColorUtil.color("#1E6458"),
                                      ColorUtil.color("#178677"),
                                      ColorUtil.color("#25C2BD"),
                                      ColorUtil.color("#46E5CB"),
                                      ColorUtil.color("#14706D"),
                                    ],
                                    stops: const [0, 0, .53, 1, 1],
                                  ),
                                ),
                          child: Center(child: Text("发送", style: TextStyle(fontSize: Global.ds(16), color: ColorUtil.color("#FAFAFA")))),
                        ),
                      ),
                    ],
                  ),
                ),
              )
            ],
          ),
        ),
        PTTState(
          builder: (context, state) => Column(
            crossAxisAlignment: CrossAxisAlignment.stretch,
            children: [
              Container(
                alignment: Alignment.centerLeft,
                color: ColorUtil.color("#192847"),
                padding: EdgeInsets.symmetric(horizontal: Global.ds(15), vertical: Global.ds(10)),
                child: Text("语音短信（限时5秒）", style: TextStyle(fontSize: Global.ds(14), color: ColorUtil.color("#2CA6E0"))),
              ),
              Container(
                color: ColorUtil.color("#144D93"),
                padding: EdgeInsets.all(Global.ds(10)),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.stretch,
                  children: [
                    Row(
                      children: [
                        Expanded(
                          child: Container(
                            height: Global.ds(40),
                            alignment: Alignment.center,
                            clipBehavior: Clip.antiAlias,
                            decoration: BoxDecoration(color: Colors.white, borderRadius: BorderRadius.circular(Global.ds(8))),
                            child: state
                                ? Row(
                                    mainAxisAlignment: MainAxisAlignment.center,
                                    children: [
                                      Text("录音中", style: TextStyle(fontSize: Global.ds(18), color: ColorUtil.color("#25CAD5"))),
                                      VerticalDivider(width: Global.ds(20), color: Colors.transparent),
                                      ImageUtil.icon("static/images/icon/11.png", size: Global.ds(24), color: ColorUtil.color("#25CAD5")),
                                    ],
                                  )
                                : Text("按下PTT录音", style: TextStyle(fontSize: Global.ds(18), color: Colors.black)),
                          ),
                        ),
                        Padding(
                          padding: EdgeInsets.symmetric(horizontal: Global.ds(50)),
                          child: Text.rich(
                            TextSpan(children: [TextSpan(text: "5", style: TextStyle(fontSize: Global.ds(36))), TextSpan(text: "秒", style: TextStyle(fontSize: Global.ds(18)))]),
                            style: const TextStyle(color: Colors.white),
                          ),
                        ),
                      ],
                    ),
                    Divider(height: Global.ds(10), color: Colors.transparent),
                    Container(
                      clipBehavior: Clip.antiAlias,
                      padding: EdgeInsets.symmetric(horizontal: Global.ds(20)),
                      decoration: BoxDecoration(color: Colors.white, borderRadius: BorderRadius.circular(Global.ds(8))),
                      child: Row(
                        children: [
                          Expanded(
                            child: state
                                ? Center(child: Text("通信中！", style: TextStyle(fontSize: Global.ds(18), color: ColorUtil.color("#25CAD5"))))
                                : Column(
                                    mainAxisAlignment: MainAxisAlignment.center,
                                    children: [
                                      Text("通信断开", style: TextStyle(fontSize: Global.ds(18), color: ColorUtil.color("#D95348"))),
                                      Text("按下PTT接通通信", style: TextStyle(fontSize: Global.ds(18), color: ColorUtil.color("#D95348")))
                                    ],
                                  ),
                          ),
                          Padding(
                            padding: EdgeInsets.only(top: Global.ds(15)),
                            child: Row(
                              mainAxisAlignment: MainAxisAlignment.spaceBetween,
                              crossAxisAlignment: CrossAxisAlignment.end,
                              children: [
                                state
                                    ? ImageUtil.asset("static/images/ptt/opened.png", width: Global.ds(29), height: Global.ds(46))
                                    : AnimatedLoop(
                                        duration: const Duration(seconds: 1),
                                        builder: (animation, child) => SlideTransition(
                                          position: Tween<Offset>(begin: const Offset(-1, 0), end: const Offset(0, 0)).animate(animation),
                                          child: FadeTransition(opacity: animation, child: child),
                                        ),
                                        child: ImageUtil.asset("static/images/ptt/closed.png", width: Global.ds(29), height: Global.ds(59)),
                                      ),
                                ImageUtil.asset("static/images/ptt/body.png", width: Global.ds(153), height: Global.ds(71)),
                              ],
                            ),
                          ),
                        ],
                      ),
                    )
                  ],
                ),
              ),
            ],
          ),
        ),
        PTTState(
          builder: (context, state) => Column(
            crossAxisAlignment: CrossAxisAlignment.stretch,
            children: [
              Container(
                alignment: Alignment.centerLeft,
                color: ColorUtil.color("#192847"),
                padding: EdgeInsets.symmetric(horizontal: Global.ds(15), vertical: Global.ds(10)),
                child: Text("数字通话", style: TextStyle(fontSize: Global.ds(14), color: ColorUtil.color("#2CA6E0"))),
              ),
              Container(
                color: ColorUtil.color("#144D93"),
                padding: EdgeInsets.all(Global.ds(10)),
                child: Container(
                  clipBehavior: Clip.antiAlias,
                  padding: EdgeInsets.symmetric(horizontal: Global.ds(20)),
                  decoration: BoxDecoration(color: Colors.white, borderRadius: BorderRadius.circular(Global.ds(8))),
                  child: Row(
                    children: [
                      Expanded(
                        child: state
                            ? Center(child: Text("通信中！", style: TextStyle(fontSize: Global.ds(18), color: ColorUtil.color("#25CAD5"))))
                            : Column(
                                mainAxisAlignment: MainAxisAlignment.center,
                                children: [
                                  Text("通信断开", style: TextStyle(fontSize: Global.ds(18), color: ColorUtil.color("#D95348"))),
                                  Text("按下PTT接通通信", style: TextStyle(fontSize: Global.ds(18), color: ColorUtil.color("#D95348")))
                                ],
                              ),
                      ),
                      Padding(
                        padding: EdgeInsets.only(top: Global.ds(15)),
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          crossAxisAlignment: CrossAxisAlignment.end,
                          children: [
                            state
                                ? ImageUtil.asset("static/images/ptt/opened.png", width: Global.ds(29), height: Global.ds(46))
                                : AnimatedLoop(
                                    duration: const Duration(seconds: 1),
                                    builder: (animation, child) => SlideTransition(
                                      position: Tween<Offset>(begin: const Offset(-1, 0), end: const Offset(0, 0)).animate(animation),
                                      child: FadeTransition(opacity: animation, child: child),
                                    ),
                                    child: ImageUtil.asset("static/images/ptt/closed.png", width: Global.ds(29), height: Global.ds(59)),
                                  ),
                            ImageUtil.asset("static/images/ptt/body.png", width: Global.ds(153), height: Global.ds(71)),
                          ],
                        ),
                      ),
                    ],
                  ),
                ),
              ),
            ],
          ),
        ),
        PTTState(
          builder: (context, state) => Column(
            crossAxisAlignment: CrossAxisAlignment.stretch,
            children: [
              Container(
                alignment: Alignment.centerLeft,
                color: ColorUtil.color("#192847"),
                padding: EdgeInsets.symmetric(horizontal: Global.ds(15), vertical: Global.ds(10)),
                child: Text("模拟通话", style: TextStyle(fontSize: Global.ds(14), color: ColorUtil.color("#2CA6E0"))),
              ),
              Container(
                color: ColorUtil.color("#144D93"),
                padding: EdgeInsets.all(Global.ds(10)),
                child: Container(
                  clipBehavior: Clip.antiAlias,
                  padding: EdgeInsets.symmetric(horizontal: Global.ds(20)),
                  decoration: BoxDecoration(color: Colors.white, borderRadius: BorderRadius.circular(Global.ds(8))),
                  child: Row(
                    children: [
                      Expanded(
                        child: state
                            ? Center(child: Text("通信中！", style: TextStyle(fontSize: Global.ds(18), color: ColorUtil.color("#25CAD5"))))
                            : Column(
                                mainAxisAlignment: MainAxisAlignment.center,
                                children: [
                                  Text("通信断开", style: TextStyle(fontSize: Global.ds(18), color: ColorUtil.color("#D95348"))),
                                  Text("按下PTT接通通信", style: TextStyle(fontSize: Global.ds(18), color: ColorUtil.color("#D95348")))
                                ],
                              ),
                      ),
                      Padding(
                        padding: EdgeInsets.only(top: Global.ds(15)),
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          crossAxisAlignment: CrossAxisAlignment.end,
                          children: [
                            state
                                ? ImageUtil.asset("static/images/ptt/opened.png", width: Global.ds(29), height: Global.ds(46))
                                : AnimatedLoop(
                                    duration: const Duration(seconds: 1),
                                    builder: (animation, child) => SlideTransition(
                                      position: Tween<Offset>(begin: const Offset(-1, 0), end: const Offset(0, 0)).animate(animation),
                                      child: FadeTransition(opacity: animation, child: child),
                                    ),
                                    child: ImageUtil.asset("static/images/ptt/closed.png", width: Global.ds(29), height: Global.ds(59)),
                                  ),
                            ImageUtil.asset("static/images/ptt/body.png", width: Global.ds(153), height: Global.ds(71)),
                          ],
                        ),
                      ),
                    ],
                  ),
                ),
              ),
            ],
          ),
        ),
      ][current!];

  void sendText(StateSetter stateSetter) {
    String content = _input1Controller.value.text;
    if (content.isEmpty) {
      ToastUtil.error("请输入内容");
    } else {
      context.read<ChatNotifier>().sendText(radioId!, content).then((value) => stateSetter(() => _input1Controller.clear()));
    }
  }

  @override
  bool get wantKeepAlive => true;
}

class PTTState extends StatefulWidget {
  final Widget Function(BuildContext context, bool state) builder;

  const PTTState({super.key, required this.builder});

  @override
  State<PTTState> createState() => _PTTStateState();
}

class _PTTStateState extends State<PTTState> {
  bool opened = false;

  @override
  Widget build(BuildContext context) => widget.builder(context, opened);
}
